/** * @param $mode * @return array */ public function depthFirst($mode) { /** * @var BinaryTreeNode $root */ $root = $this->getRoot(); // uses a Stack $resultArray = []; $stack = new Stack(); switch ($mode) { case self::SEARCH_PRE_ORDER: /*current + left + right */ $current = $root; $stack->push($current); array_push($resultArray, $current->getData()); while (!$stack->isEmpty()) { if ($current->getLeft() !== null and !in_array($current->getLeft()->getData(), $resultArray)) { $current = $current->getLeft(); $stack->push($current); array_push($resultArray, $current->getData()); } elseif ($current->getRight() !== null and !in_array($current->getRight()->getData(), $resultArray)) { $current = $current->getRight(); $stack->push($current); array_push($resultArray, $current->getData()); } else { $stack->pop(); $current = $current->getParent(); } } break; case self::SEARCH_IN_ORDER: /*left + current + right */ $current = $root; $stack->push($current); while (!$stack->isEmpty()) { if ($current->getLeft() !== null and !in_array($current->getLeft()->getData(), $resultArray)) { $current = $current->getLeft(); $stack->push($current); } elseif ($current->getRight() !== null and !in_array($current->getRight()->getData(), $resultArray)) { array_push($resultArray, $current->getData()); $current = $current->getRight(); $stack->push($current); } else { if (!in_array($current->getData(), $resultArray)) { array_push($resultArray, $current->getData()); } $stack->pop(); $current = $current->getParent(); } } break; case self::SEARCH_POST_ORDER: /*left + right + current */ $current = $root; $stack->push($current); while (!$stack->isEmpty()) { if ($current->getLeft() !== null and !in_array($current->getLeft()->getData(), $resultArray)) { $current = $current->getLeft(); $stack->push($current); } elseif ($current->getRight() !== null and !in_array($current->getRight()->getData(), $resultArray)) { $current = $current->getRight(); $stack->push($current); } else { if (!in_array($current->getData(), $resultArray)) { array_push($resultArray, $current->getData()); } $stack->pop(); $current = $current->getParent(); } } break; } return $resultArray; }
public function testPeek() { $data = $this->generateData(); $this->stack->push($data); self::assertEquals($data, $this->stack->peek()); }