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

Powered by Blogger.

Sunday, September 10, 2017

Level Order Traversal line by line


Idea is to keep track upon null value whenever detected print $ and check if q is nt  empty means we are still left with nodes so add null to end of Q.

Code:

 void levelOrder(Node node) 
    {
        if(node==null)
        return;
        Queue<Node> q=new LinkedList<Node>();
        q.add(node);
        q.add(null);
        while(!q.isEmpty())
        {
            Node t=q.removeFirst();
            if(t!=null)
            {
                System.out.print(t.data+" ");
             if(t.left!=null)
            q.add(t.left);
            if(t.right!=null)
            q.add(t.right);
                
            }
            else
           {System.out.print("$ ");
           if(!q.isEmpty())
            q.add(null);}
        }
    }

0 Comments:

Post a Comment

Stats