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;
}
}
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