Please let me know your thoughts on the code below, please be brutal. Here is the question I solved:
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] ]
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root==null){
return res;
}
ArrayList<Integer> level = new ArrayList<Integer>();
level.add(root.val);
res.add(level);
int depth=1;
queue.add(root);
TreeNode empty = new TreeNode(2);
queue.add(null);
level = new ArrayList<Integer>();
while(!queue.isEmpty()){
TreeNode curr = queue.poll();
if(curr==null){
if(!queue.isEmpty()){
queue.add(null);
}
else{
break;
}
res.add(level);
level = new ArrayList<Integer>();
depth++;
}
else{
if(depth%2==0){
if(curr.left!=null){
level.add(curr.left.val);
queue.add(curr.left);
}
if(curr.right!=null){
level.add(curr.right.val);
queue.add(curr.right);
}
}
else{
if(curr.right!=null){
level.add(curr.right.val);
queue.add(curr.right);
}
if(curr.left!=null){
level.add(curr.left.val);
queue.add(curr.left);
}
}
}
}
return res;
}