-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 170.java
More file actions
44 lines (32 loc) · 1.07 KB
/
Day 170.java
File metadata and controls
44 lines (32 loc) · 1.07 KB
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
class Solution {
static class Pair {
Node node;
int hd;
Pair(Node node, int hd) {
this.node = node;
this.hd = hd;
}
}
public ArrayList<ArrayList<Integer>> verticalOrder(Node root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (root == null) return result;
TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>();
Queue<Pair> queue = new LinkedList<>();
queue.offer(new Pair(root, 0));
while (!queue.isEmpty()) {
Pair current = queue.poll();
Node node = current.node;
int hd = current.hd;
map.putIfAbsent(hd, new ArrayList<>());
map.get(hd).add(node.data);
if (node.left != null)
queue.offer(new Pair(node.left, hd - 1));
if (node.right != null)
queue.offer(new Pair(node.right, hd + 1));
}
for (ArrayList<Integer> list : map.values()) {
result.add(list);
}
return result;
}
}