Collections.reverse()

essentially level order.

dfs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
dfs(root, res, 0);
Collections.reverse(res);
return res;
}
public void dfs(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);
dfs(node.left, res, depth+1);
dfs(node.right, res, depth+1);
}
}

bfs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
List<Integer> tmp = new LinkedList<>();
int count = q.size();
// each level : 1 for loop
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);
tmp.add(q.poll().val);
}
res.add(tmp);
}
Collections.reverse(res);
return res;
}
}