22 Oct 2013

Level Order Traversal

Problem Statement: 
     Print Level order traversal of Binary Tree (Using Queue)

Fig Level order traversal of Binary Tree

Required Output:  1  2  3  4  5  6  7  8  9 10  11  12

Solution : 
            
Level order traversal of a binary tree also means BFS (Breadth First Search) , in which each children of a node is processed , then the the subsequent nodes unlike DFS(Depth First Search).
    
Please refer Source Code here


 1 
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public void printLevelOrder(Node root){
  if(root==null)
   return ;
  
  LinkedList<Node> queue = new LinkedList<Node>();
  queue.addLast(root);
  queue.addLast(null);
  
  while(!queue.isEmpty()){
   Node poped = queue.removeFirst(); //dequeue  

   if (poped == null) {     
    if(queue.isEmpty()) // if last node , terminate
     continue;
    queue.addLast(null);
    System.out.println();
   } 
   else {
    
    System.out.print(poped.data + "\t");   
    
    if (poped.left != null)
    queue.addLast(poped.left);
    if (poped.right != null)
    queue.addLast(poped.right);
   }
  }
 }

Please post comments if any suggestion or discrepancy. 

Happy Coding !! :)

No comments:

Post a Comment