leetcode--Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer> > result = new ArrayList<List<Integer> >();
		if(root != null){
			Stack<TreeNode> topLevel = new Stack<TreeNode>();
			topLevel.push(root);
			int reverse = 1;
			while(!topLevel.isEmpty()) {
				Stack<TreeNode> nextLevel = new Stack<TreeNode>();
				List<Integer> value = new ArrayList<Integer>();
				while(!topLevel.isEmpty()) {
					TreeNode node = topLevel.pop();
					value.add(node.val);
					if(reverse % 2 == 1){
					    if(node.left != null)
						    nextLevel.push(node.left);
					    if(node.right != null)
						    nextLevel.push(node.right);
					}
					else{
					    if(node.right != null)
						    nextLevel.push(node.right);
					    if(node.left != null)
						    nextLevel.push(node.left);
					}
				}
				++reverse; 
				result.add(value);
				topLevel = nextLevel;
			}
		}
		return result;    
    }
}

  

posted @ 2014-06-05 11:20  Averill Zheng  阅读(160)  评论(0编辑  收藏  举报