-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 169.java
More file actions
46 lines (35 loc) · 1.06 KB
/
Day 169.java
File metadata and controls
46 lines (35 loc) · 1.06 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
class Solution {
class Pair {
Node node;
int hd;
Pair(Node node, int hd){
this.node = node;
this.hd = hd;
}
}
public ArrayList<Integer> topView(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if(root == null) return result;
TreeMap<Integer, Integer> map = new TreeMap<>();
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(root, 0));
while(!q.isEmpty()){
Pair p = q.poll();
Node node = p.node;
int hd = p.hd;
if(!map.containsKey(hd)){
map.put(hd, node.data);
}
if(node.left != null){
q.add(new Pair(node.left, hd - 1));
}
if(node.right != null){
q.add(new Pair(node.right, hd + 1));
}
}
for(int val : map.values()){
result.add(val);
}
return result;
}
}