-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTopViewOfBinaryTree
More file actions
42 lines (40 loc) · 1.05 KB
/
TopViewOfBinaryTree
File metadata and controls
42 lines (40 loc) · 1.05 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
class Q
{
Node temp;
int hd;
Q(Node t, int h)
{
temp = t;
hd = h;
}
}
class View
{
// function should print the topView of the binary tree
static void topView(Node root)
{
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
if(root == null)
return;
Queue<Q> q = new LinkedList<Q>();
q.add(new Q(root, 0));
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
while(!q.isEmpty())
{
Q obj = q.poll();
if(hm.get(obj.hd) == null)
hm.put(obj.hd, obj.temp.data);
if(obj.temp.left != null)
q.add(new Q(obj.temp.left, obj.hd-1));
if(obj.temp.right != null)
q.add(new Q(obj.temp.right, obj.hd+1));
if(obj.hd < min)
min = obj.hd;
if(obj.hd > max)
max = obj.hd;
}
for(int i=min ; i<=max ; i++)
{
System.out.print(hm.get(i) + " ");
}
}