Wednesday, February 27, 2013
[LeetCode] Binary Tree Zigzag Level Order Traversal
Thought:
Basically the same with level order traversal. And a flag should be used for determining the order of some specific level.
Code:
public class Solution {
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int depth = 0;
Queue<TreeNode> q1 = new LinkedList<TreeNode>();
Queue<Integer> q2 = new LinkedList<Integer>();
if(root == null) return result;
q1.offer(root);
q2.offer(depth + 1);
while(q1.peek() != null) {
TreeNode element = q1.poll();
depth = q2.poll();
if(result.size() < depth) {
result.add(new ArrayList<Integer>());
}
if(depth % 2 == 1) {
result.get(depth - 1).add(element.val);
}else{
result.get(depth - 1).add(0,element.val);
}
if(element.left != null) {
q1.offer(element.left);
q2.offer(depth+1);
}
if(element.right != null) {
q1.offer(element.right);
q2.offer(depth+1);
}
}
return result;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment