`
hcx2013
  • 浏览: 88910 次
社区版块
存档分类
最新评论

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]
]


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    	List<List<Integer>> res = new ArrayList<List<Integer>>(); 
    	if (root == null) {
    		return res;
    	}
    	LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 
    	queue.add(root);
    	Boolean reverse = false;
    	int cur = 1;
    	int next = 0;
    	ArrayList<Integer> levelres = new ArrayList<Integer>();  
    	while (!queue.isEmpty()) {
    		TreeNode poll = queue.poll();
    		cur--;
    		levelres.add(poll.val);
    		if (poll.left != null) {
    			queue.add(poll.left);
    			next++;
    		}
    		if (poll.right != null) {
    			queue.add(poll.right);
    			next++;
    		}
    		if (cur == 0) {
    			cur = next;
    			next = 0;
    			if (reverse) {
    				Collections.reverse(levelres);
    			} 
    			reverse = !reverse;
    			res.add(levelres);
    			levelres = new ArrayList<Integer>(); 
    		}
    	}
    	return res;
    }
}
 
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics