/** * Depth-first pre-order (without recursion) * In this case we have to use a Stack. * * @param \DataStructure\BinaryTree\Tree $tree */ function depth_first_traversal(Tree $tree) { $root = $tree->getRoot(); if ($root === null) { return; } $stack = new Stack(); $stack->push($root); while (!$stack->isEmpty()) { $node = $stack->pop(); var_dump($node->value); if ($node->right !== null) { $stack->push($node->right); } if ($node->left !== null) { $stack->push($node->left); } } }
/** * Breadth-first traversal uses a Queue instead od a Stack. * * @param \DataStructure\BinaryTree\Tree $tree */ function breadth_first_traversal(Tree $tree) { $root = $tree->getRoot(); if ($root === null) { return; } $queue = new Queue(); $queue->push($root); while (!$queue->isEmpty()) { $node = $queue->pop(); var_dump($node->value); if ($node->left !== null) { $queue->push($node->left); } if ($node->right !== null) { $queue->push($node->right); } } }