-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.java
47 lines (39 loc) · 937 Bytes
/
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
class Node
int data;
Node left;
Node right;
*/
public static void topView(Node root) {
class Pair {
Node n;
int p;
Pair(Node n, int p) {
this.n = n;
this.p = p;
}
}
int[] values = new int[500 + 1];
for (int i = 0; i < 500 + 1; i++) {
values[i] = -1;
}
LinkedList<Pair> queue = new LinkedList<>();
queue.push(new Pair(root, 250));
while (!queue.isEmpty()) {
Pair current = queue.pop();
if (values[current.p] == -1) {
values[current.p] = current.n.data;
}
if (current.n.left != null) {
queue.add(new Pair(current.n.left, current.p - 1));
}
if (current.n.right != null) {
queue.add(new Pair(current.n.right, current.p + 1));
}
}
for (int i = 0; i < 500 + 1; i++) {
if (values[i] != -1) {
System.out.print(values[i] + " ");
}
}
}