-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBottomView.java
More file actions
45 lines (33 loc) · 1.03 KB
/
BottomView.java
File metadata and controls
45 lines (33 loc) · 1.03 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
package Trees;
import java.util.*;
public class BottomView {
static void printBottomView(Node root) {
if (root == null) return;
HashMap<Integer, Integer> hash = new HashMap<>();
int leftmost = 0;
Queue<Pair> q = new ArrayDeque<>();
q.add(new Pair(root, 0));
while (!q.isEmpty()) {
Pair top = q.remove();
Node temp = top.node;
int index = top.second;
hash.put(index, temp.val);
leftmost = Math.min(index, leftmost);
if (temp.left != null) q.add(new Pair(temp.left, index - 1));
if (temp.right != null) q.add(new Pair(temp.right, index + 1));
}
while (hash.containsKey(leftmost)) {
System.out.print(hash.get(leftmost++) + " ");
}
}
public static void main(String[] args) {
}
static class Pair {
Node node;
int second;
Pair(Node node, int second) {
this.node = node;
this.second = second;
}
}
}