Wednesday, April 23, 2014

Printing a Binary Tree in Zig Zag Level-Order


Solution:
This problem can be solved easily using two stacks (one called currentLevel and the other one called nextLevel). You would also need a variable to keep track of the current level’s order (whether it is left->right or right->left).
You pop from stack currentLevel and print the node’s value. Whenever the current level’s order is from left->right, you push the node’s left child, then its right child to stack nextLevel. Remember a Stack is a Last In First OUT (LIFO) structure, so the next time when nodes are popped off nextLevel, it will be in the reverse order.
On the other hand, when the current level’s order is from right->left, you would push the node’s right child first, then its left child. Finally, don’t forget to swap those two stacks at the end of each level (ie, when currentLevel is empty).

static void zigzagTraversal(Node root){
if(root == null) return;

Stack<Node> currLevel, nextLevel = null;
currLevel = new Stack<Node>();
nextLevel = new Stack<Node>();

currLevel.push(root);
boolean lefttoright = true;

while(!currLevel.isEmpty())
{
Node currNode = currLevel.pop();
//System.out.print(currNode.val+" ");
if(currNode != null)
{
System.out.print(currNode.val+" ");
if(lefttoright){
if(currNode.left != null)
nextLevel.push(currNode.left);
if(currNode.right != null)
nextLevel.push(currNode.right);
}else{
if(currNode.right != null)
nextLevel.push(currNode.right);
if(currNode.left != null)
nextLevel.push(currNode.left);
}
}
if(currLevel.isEmpty())
{
System.out.println();
lefttoright = !lefttoright;
Stack<Node> tmp = currLevel;
currLevel = nextLevel;
nextLevel = tmp;
}
}

}


References:
http://leetcode.com/2010/09/printing-binary-tree-in-zig-zag-level_18.html

No comments:

Post a Comment