forked from striver79/FreeKaTreeSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathL22_topViewOfBtJava
33 lines (29 loc) · 1006 Bytes
/
L22_topViewOfBtJava
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
class Solution
{
//Function to return a list of nodes visible from the top view
//from left to right in Binary Tree.
static ArrayList<Integer> topView(Node root)
{
ArrayList<Integer> ans = new ArrayList<>();
if(root == null) return ans;
Map<Integer, Integer> map = new TreeMap<>();
Queue<Pair> q = new LinkedList<Pair>();
q.add(new Pair(root, 0));
while(!q.isEmpty()) {
Pair it = q.remove();
int hd = it.hd;
Node temp = it.node;
if(map.get(hd) == null) map.put(hd, temp.data);
if(temp.left != null) {
q.add(new Pair(temp.left, hd - 1));
}
if(temp.right != null) {
q.add(new Pair(temp.right, hd + 1));
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
ans.add(entry.getValue());
}
return ans;
}
}