forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
33 lines (32 loc) · 1.07 KB
/
Solution.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
class Solution {
public List<List<Integer>> verticalTraversal(TreeNode root) {
List<int[]> list = new ArrayList<>();
dfs(root, 0, 0, list);
list.sort(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] != o2[0]) return Integer.compare(o1[0], o2[0]);
if (o1[1] != o2[1]) return Integer.compare(o2[1], o1[1]);
return Integer.compare(o1[2], o2[2]);
}
});
List<List<Integer>> res = new ArrayList<>();
int preX = 1;
for (int[] cur : list) {
if (preX != cur[0]) {
res.add(new ArrayList<>());
preX = cur[0];
}
res.get(res.size() - 1).add(cur[2]);
}
return res;
}
private void dfs(TreeNode root, int x, int y, List<int[]> list) {
if (root == null) {
return;
}
list.add(new int[]{x, y, root.val});
dfs(root.left, x - 1, y - 1, list);
dfs(root.right, x + 1, y - 1, list);
}
}