-
Notifications
You must be signed in to change notification settings - Fork 1
/
Binary Tree Level Order Traversal II
61 lines (60 loc) · 1.86 KB
/
Binary Tree Level Order Traversal II
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
51
52
53
54
55
56
57
58
59
60
61
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<List<Integer>> list = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root == null) return res;
dfs(root, 0);
Collections.sort(list, new Comparator<List<Integer>>(){
public int compare(List<Integer> o1, List<Integer> o2){
return -(o1.get(1) - o2.get(1));
}
});
//System.out.println(list);
List<Integer> temp = new ArrayList<>();
int prev = list.get(0).get(1);
for(int i = 0; i<list.size(); i++){
if(list.get(i).get(1) == prev){
temp.add(list.get(i).get(0));
}
else{
prev = list.get(i).get(1);
//System.out.println(temp);
res.add(new ArrayList<Integer>(temp));
temp = new ArrayList<Integer>();
temp.add(list.get(i).get(0));
}
}
if(list.size() > 0){
temp = new ArrayList<>();
temp.add(list.get(list.size()-1).get(0));
res.add(new ArrayList<Integer>(temp));
}
return res;
}
public void dfs(TreeNode root, int depth){
if(root == null){
return ;
}
List<Integer> temp = new ArrayList<>();
temp.add(root.val);
temp.add(depth);
list.add(new ArrayList<Integer>(temp));
dfs(root.left, depth+1);
dfs(root.right, depth+1);
}
}