1
+ // Java program to print top view of Binary tree
2
+ import java .util .*;
3
+
4
+ // Class for a tree node
5
+ class TreeNode
6
+ {
7
+ // Members
8
+ int key ;
9
+ TreeNode left , right ;
10
+
11
+ // Constructor
12
+ public TreeNode (int key )
13
+ {
14
+ this .key = key ;
15
+ left = right = null ;
16
+ }
17
+ }
18
+
19
+ // A class to represent a queue item. The queue is used to do Level
20
+ // order traversal. Every Queue item contains node and horizontal
21
+ // distance of node from root
22
+ class QItem
23
+ {
24
+ TreeNode node ;
25
+ int hd ;
26
+ public QItem (TreeNode n , int h )
27
+ {
28
+ node = n ;
29
+ hd = h ;
30
+ }
31
+ }
32
+
33
+ // Class for a Binary Tree
34
+ class Tree
35
+ {
36
+ TreeNode root ;
37
+
38
+ // Constructors
39
+ public Tree () { root = null ; }
40
+ public Tree (TreeNode n ) { root = n ; }
41
+
42
+ // This method prints nodes in top view of binary tree
43
+ public void printTopView ()
44
+ {
45
+ // base case
46
+ if (root == null ) { return ; }
47
+
48
+ // Creates an empty hashset
49
+ HashSet <Integer > set = new HashSet <>();
50
+
51
+ // Create a queue and add root to it
52
+ Queue <QItem > Q = new LinkedList <QItem >();
53
+ Q .add (new QItem (root , 0 )); // Horizontal distance of root is 0
54
+
55
+ // Standard BFS or level order traversal loop
56
+ while (!Q .isEmpty ())
57
+ {
58
+ // Remove the front item and get its details
59
+ QItem qi = Q .remove ();
60
+ int hd = qi .hd ;
61
+ TreeNode n = qi .node ;
62
+
63
+ // If this is the first node at its horizontal distance,
64
+ // then this node is in top view
65
+ if (!set .contains (hd ))
66
+ {
67
+ set .add (hd );
68
+ System .out .print (n .key + " " );
69
+ }
70
+
71
+ // Enqueue left and right children of current node
72
+ if (n .left != null )
73
+ Q .add (new QItem (n .left , hd -1 ));
74
+ if (n .right != null )
75
+ Q .add (new QItem (n .right , hd +1 ));
76
+ }
77
+ }
78
+ }
79
+
80
+ // Driver class to test above methods
81
+ public class Main
82
+ {
83
+ public static void main (String [] args )
84
+ {
85
+ /* Create following Binary Tree
86
+ 1
87
+ / \
88
+ 2 3
89
+ \
90
+ 4
91
+ \
92
+ 5
93
+ \
94
+ 6*/
95
+ TreeNode root = new TreeNode (1 );
96
+ root .left = new TreeNode (2 );
97
+ root .right = new TreeNode (3 );
98
+ root .left .right = new TreeNode (4 );
99
+ root .left .right .right = new TreeNode (5 );
100
+ root .left .right .right .right = new TreeNode (6 );
101
+ Tree t = new Tree (root );
102
+ System .out .println ("Following are nodes in top view of Binary Tree" );
103
+ t .printTopView ();
104
+ }
105
+ }
0 commit comments