Tuesday, February 19, 2013

C Program to Print level order traversal of a binary tree using queue.


To print the level order traversal of the tree we need to use Queue .For the above binary tree in the diagram level order traversal is ABCDEFG .
Solution is very simple . The steps are
1.Add root node to the queue using enqueue function
2.Get a node from queue using dequeue function and print it . If the node has children add it to the queue (enqueue)
3.Continue the step 2 until the queue is empty.

Assume that enqueue(node) funtion adds node into queue and dequeue() function deletes the node from the queue and returns node.And dequeue() function returns null when there is no node in the queue .

Code: (in C)

For the above tree execution will be
in queue : A             output:
in queue : BC           output:A
in queue : CDE         output:AB
in queue : DEFG       output:ABC
in queue : EFG         output:ABCD
in queue : FG           output:ABCDE
in queue : G             output:ABCDEF
in queue :                output:ABCDEFG

Please let me know if u have any questions .

2 comments:

ankit said...

what would be the structure of queue and will we store the address of tree nodes int it it gives type mismatch error . could u provide the complete code.

Riku said...

what would be the structure of queue and will we store the address of tree nodes int it it gives type mismatch error . could u provide the complete code please.