-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution107.java
50 lines (40 loc) · 1.01 KB
/
Solution107.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package algorithm.leetcode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* @author: mayuan
* @desc: 二叉树的层次遍历 II
* @date: 2019/03/07
*/
public class Solution107 {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (null == root) {
return ans;
}
dfs(ans, root, 0);
Collections.reverse(ans);
return ans;
}
private void dfs(List<List<Integer>> answer, TreeNode node, int depth) {
if (null == node) {
return;
}
if (answer.size() <= depth) {
answer.add(new LinkedList<>());
}
answer.get(depth).add(node.val);
dfs(answer, node.left, depth + 1);
dfs(answer, node.right, depth + 1);
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}