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

Powered by Blogger.

Sunday, August 27, 2017

Iterative PostOrder Traversal


Explanation :

http://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/

Code:


void postOrder(Node root) {
    Deque<Node> q=new ArrayDeque<Node>();
    h:
    while(true){
    while(root!=null)
        {
        if(root.right!=null)
            q.add(root.right);
        q.add(root);
        root=root.left;
    }
         root=q.removeLast();
        if(!q.isEmpty() && root.right!=null && q.peekLast().data==root.right.data)
        {
            Node last=q.removeLast();
            q.add(root);
            root=root.right;
        }
        else
        {
            System.out.print(root.data+" ");
            root=null;
        }
    if(q.isEmpty())
        break h;
    }
   
}

0 Comments:

Post a Comment

Stats