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

Powered by Blogger.

Saturday, August 26, 2017

Iterative Approach Of Preorder Traversal


Expl:

Push root .
Loop while Q is not empty , print data and push right node then left and remove from Q (last) so that we get the order

Code:

Deque<Node> q=new ArrayDeque<Node>();
        q.add(root);
    while(!q.isEmpty())
    {
        Node t=q.removeLast();
        System.out.print(t.data+" ");
        if(t.right!=null)
        {
            q.add(t.right);
        }
        if(t.left!=null)
        {
            q.add(t.left);
        }
    }

0 Comments:

Post a Comment

Stats