-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
47 lines (35 loc) · 1.1 KB
/
Copy pathsolution.java
File metadata and controls
47 lines (35 loc) · 1.1 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
45
46
47
class Solution {
public ArrayList<ArrayList<Integer>> verticalOrder(Node root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (root == null)
return result;
// Map to store vertical lines
TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>();
// Queue for BFS
Queue<Pair> queue = new LinkedList<>();
queue.add(new Pair(root, 0));
while (!queue.isEmpty()) {
Pair p = queue.poll();
Node node = p.node;
int hd = p.hd;
map.putIfAbsent(hd, new ArrayList<>());
map.get(hd).add(node.data);
if (node.left != null)
queue.add(new Pair(node.left, hd - 1));
if (node.right != null)
queue.add(new Pair(node.right, hd + 1));
}
for (ArrayList<Integer> list : map.values()) {
result.add(list);
}
return result;
}
}
class Pair {
Node node;
int hd;
Pair(Node n, int h) {
node = n;
hd = h;
}
}