This is original level order

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
level(root, res, 0);
return res;
}
public void level(TreeNode node, List<List<Integer>> res, int depth) {
if (node == null) return;
List<Integer> tmp = new LinkedList<>();
if (depth == res.size()) res.add(tmp);
res.get(depth).add(node.val);
level(node.left, res, depth+1);
level(node.right, res, depth+1);
}
}

This is zigzag level order:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
level(root, res, 0);
return res;
}
public void level(TreeNode node, List<List<Integer>> res, int depth) {
if (node == null) return;
List<Integer> tmp = new LinkedList<>();
if (depth == res.size()) res.add(tmp);
if (depth %2 != 0) {
res.get(depth).add(0, node.val);
} else {
res.get(depth).add(node.val);
}
level(node.left, res, depth+1);
level(node.right, res, depth+1);

}
}

Interesting.

bfs via queue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean flag = false;
while (!q.isEmpty()) {
int count = q.size();
List<Integer> tmp = new LinkedList<>();
for (int i = 0; i < count; ++i) {
if (q.peek().left != null) q.offer(q.peek().left);
if (q.peek().right != null) q.offer(q.peek().right);
if (flag) {
tmp.add(0, q.poll().val);
} else {
tmp.add(q.poll().val);
}
}
res.add(tmp);
flag = flag ? false : true;
}
return res;
}
}