BreadthOrderTraversal(BinaryTree binaryTree)
{
Queue queue;
queue.Enqueue(binaryTree.Root);
while(Queue.Size > 0)
{
Node n = GetFirstNodeInQueue();
queue.Enqueue(n.LeftChild); //Enqueue if exists
queue.Enqueue(n.RightChild); //Enqueue if exists
queue.Dequeue(); //Visit
}
}
BreadthOrderTraversal_1(BinaryTree binaryTree)
{
Queue queue;
queue.Enqueue(binaryTree.Root);
while(Queue.Size > 0)
{
Node n = GetFirstNodeInQueue();
queue.Enqueue(n.RightChild); //Enqueue if exists
queue.Enqueue(n.LeftChild); //Enqueue if exists
queue.Dequeue(); //Visit
}
}
This will give us output as 1 3 2 7 6 5 4 and reversing this will give 4 5 6 7 2 3 1.
BreadthOrderTraversalReverse(BinaryTree binaryTree)
{
Queue queue;
queue.Enqueue(binaryTree.Root);
while(Queue.Size > 0)
{
Node n = GetFirstNodeInQueue();
queue.Enqueue(n.RightChild); //Enqueue if exists
queue.Enqueue(n.LeftChild); //Enqueue if exists
stack.push() = queue.Dequeue(); //Visit
}
while(!isEmpty(stack))
{
process(stack.top);
stack.pop();
}
}
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.