-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtop view of binary tree .java
92 lines (79 loc) · 2.57 KB
/
top 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.*;
import java.util.*;
class code
{
static class Node
{
int data;
Node left;
Node right;
Node(int num)
{
data = num;
left = right = null;
}
};
// class definition to handle pairs
static class pair
{
int nodeData;
int height;
pair(int key,int num)
{
nodeData = key;
height = num;
}
}
/* the function performs inorder traversal and stores top view
of the binary tree.
for every node encountered during the traversal we have it's :
w -> horizontal depth(width)
h -> vertical depth(height)
*/
static void inorder(Node root,int w,int h, TreeMap <Integer,pair> Map)
{
if(root == null)
return;
inorder(root.left,w-1,h+1,Map);
/* check if a particular horizontal level has been visited or not */
if(!Map.containsKey(w))
Map.put(w,new pair(root.data,h));
/* if particular horizontal level has been visited
then check if height of current node is less than
the previous node met at same horizontal level, if this
is true then the current node should replace previous node
in top view of the binary tree */
else if(Map.get(w).height > h)
Map.put(w,new pair(root.data,h));
inorder(root.right,w+1,h+1,Map);
}
/* function should print the topView of
the binary tree */
static void topView(Node root)
{
if(root == null)
return;
/* map to store node at each vertical(horizontal) distance(Level)
i.e. stores top view */
TreeMap<Integer,pair> Map = new TreeMap<>();
// obtain top view of binary tree into the Map
inorder(root,0,0,Map);
/* traverse the map and print top view */
for (Map.Entry<Integer, pair> i : Map.entrySet())
System.out.print(i.getValue().nodeData+" ");
}
/* main function to implement above function */
public static void main (String[] args)
{
/* construct the binary tree */
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.right = new Node(5);
root.left.right = new Node(4);
root.left.right.right = new Node(6);
root.left.right.right.right = new Node(7);
root.left.right.right.right.right = new Node(8);
topView(root);
}
}