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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Node Structure : | |
struct node | |
{ | |
int data; | |
struct node* left; | |
struct node* right; | |
}; | |
void level_order_traversal(struct node* root) | |
{ | |
if(root==null) | |
return; | |
enqueue(root); | |
struct node* temp=dequeue(); | |
while(temp!=null) | |
{ | |
printf("%d ",temp->data); | |
if(node->left!=null) | |
enqueue(node->left); | |
if(node->right) | |
enqueue(node->right); | |
temp=dequeue(); | |
} | |
} |
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:
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.
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.
Post a Comment