Description: Given a tree, we have to print level order traversal of the tree. Level-order traversal means traversing the tree level-by-level , generally in a top down fashion.

 
If video does not load, Click here
 
Example:
 

In the example below, level order traversal would be:

 

1->3->2->5->4

 
Algorithm:

 

1.Create a FIFO queue Q.

2.Assign a variable pointer ‘temp’ as the root element.

3.While (temp!=NULL)

  {

  -Print temp->data

  -Put left child of temp(temp->left) on queue Q

  -Put right child of temp(temp->right) on queue Q

  -Dequeue a node from queue Q, and assign its value to ‘temp’.

  }

 

Time Complexity:

 

O(n), where 'n' is the number of nodes in the tree.

Go to top