-
Notifications
You must be signed in to change notification settings - Fork 17
/
BottomView.java
64 lines (47 loc) · 1.6 KB
/
BottomView.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution
{
static class Pair {
Node node;
int level;
public Pair(Node node, int level) {
this.node = node;
this.level = level;
}
}
static int min=0, max=0;
public void findminmax(Node root, int h) {
if(root == null) return;
min = Math.min(min, h);
max = Math.max(max, h);
findminmax(root.left, h-1);
findminmax(root.right, h+1);
}
public ArrayList <Integer> bottomView(Node root) {
findminmax(root, 0);
ArrayList<Integer> list = new ArrayList<>();
if(root == null) return list;
ArrayList<Integer> ans[] = new ArrayList[max-min+1];
for(int i=0; i<ans.length; i++) {
ans[i] = new ArrayList<>();
}
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(root, -min));
while(!q.isEmpty()) {
int size = q.size();
for(int i=1; i<=size; i++) {
Pair p = q.poll();
ans[p.level].add(p.node.data);
if(p.node.left != null) q.add(new Pair(p.node.left, p.level-1));
if(p.node.right != null) q.add(new Pair(p.node.right, p.level+1));
}
}
for(int i=0; i<ans.length; i++) {
if(!ans[i].isEmpty()) {
int s = ans[i].size()-1;
int value = ans[i].get(s);
list.add(value);
}
}
return list;
}
}