-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopView.java
More file actions
57 lines (43 loc) · 1.26 KB
/
TopView.java
File metadata and controls
57 lines (43 loc) · 1.26 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
48
49
50
51
52
53
54
55
56
package Trees;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class TopView {
static void topView(Node root) {
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(root, 0));
int hd, l = 0, r = 0;
Stack<Integer> left = new Stack<>();
ArrayList<Integer> right = new ArrayList<>();
Node node;
while (!q.isEmpty()) {
node = q.peek().node;
hd = q.peek().hd;
if (hd < l) {
left.push(node.val);
l = hd;
}
if (hd > r) {
right.add(node.val);
r = hd;
}
if (node.left != null) q.add(new Pair(node.left, hd - 1));
if (node.right != null) q.add(new Pair(node.right, hd + 1));
q.poll();
}
while (!left.isEmpty()) System.out.print(left.pop() + " ");
System.out.print(root.val + " ");
for (int num : right) System.out.print(num + " ");
}
public static void main(String[] args) {
}
static class Pair {
Node node;
int hd;
Pair(Node node, int hd) {
this.node = node;
this.hd = hd;
}
}
}