-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBottom View of Binary Tree.java
51 lines (49 loc) · 1.32 KB
/
Bottom View of Binary Tree.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
class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = right = null;
}
}
class Pair {
Node node;
int dist;
public Pair(Node node, int dist) {
this.node = node;
this.dist = dist;
}
}
class Solution
{
private void rec(Node root, List<List<Integer>> arr, int d) {
}
//Function to return a list containing the bottom view of the given tree.
public ArrayList<Integer> bottomView(Node root)
{
// Code here
ArrayList<Integer> sol = new ArrayList<>();
Map<Integer, Integer> map = new TreeMap<>();
// rec(root, arr, 0);
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(root, 0));
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Pair p = q.poll();
map.put(p.dist, p.node.data);
if (p.node.left != null) {
q.add(new Pair(p.node.left, p.dist - 1));
}
if (p.node.right != null) {
q.add(new Pair(p.node.right, p.dist + 1));
}
}
}
for (Map.Entry<Integer, Integer> me : map.entrySet()) {
sol.add(me.getValue());
}
return sol;
}
}