Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, May 14, 2017

Level Order Traversal tree


   /*
   
    class Node
       int data;
       Node left;
       Node right;
   */
   void LevelOrder(Node root)
    {
      if(!(root instanceof Node))
          return;
       Queue<Node> node=new LinkedList<Node>();
       node.add(root);
       while(!(node.isEmpty()))
           {
           Node temp=node.remove();
           System.out.print(temp.data+" ");
           if(temp.left!=null)
               node.add(temp.left);
           if(temp.right!=null)
               node.add(temp.right);
       }
     
    }


Explanation :

check if root is null(tree is empty)
Create a queue which can hold the node(children) of current node so that it can be traversed in the level order. 

0 Comments:

Post a Comment

Stats