File tree 1 file changed +104
-0
lines changed
1 file changed +104
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* Hacker Blocks */
2
+ /* Title - Tree Top View */
3
+ /* Created By - Akash Modak */
4
+ /* Date - 26/10/2020 */
5
+
6
+ // Given a binary tree , print the nodes in left to right manner as visible from above the tree
7
+
8
+ // Input Format
9
+ // Level order input for the binary tree will be given.
10
+
11
+ // Constraints
12
+ // No of nodes in the tree can be less than or equal to 10^7
13
+
14
+ // Output Format
15
+ // A single line containing space separated integers representing the top view of the tree
16
+
17
+ // Sample Input
18
+ // 1 2 3 4 5 6 -1 -1 -1 -1 -1 -1 -1
19
+ // Sample Output
20
+ // 4 2 1 3
21
+ // Explanation
22
+ // The tree looks like
23
+
24
+ // 1
25
+ // / \
26
+ // 2 3
27
+ // / \ /
28
+ // 4 5 6
29
+ // When viewed from the top , we would see the nodes 4, 2, 1 and 3.
30
+
31
+ #include < bits/stdc++.h>
32
+ using namespace std ;
33
+ class node {
34
+ public:
35
+ int data;
36
+ int hd;
37
+ node* left;
38
+ node* right;
39
+ node (int d){
40
+ data = d;
41
+ left=right=NULL ;
42
+ }
43
+ };
44
+
45
+ node* build (){
46
+ int d;
47
+ cin>>d;
48
+ if (d==-1 )
49
+ return NULL ;
50
+ int hd = 0 ;
51
+ queue<node*> q;
52
+ node * root = new node (d);
53
+ q.push (root);
54
+
55
+ while (!q.empty ()){
56
+ node* temp = q.front ();
57
+ q.pop ();
58
+ cin>>d;
59
+ if (d!=-1 ){
60
+ temp->left = new node (d);
61
+ q.push (temp->left );
62
+ }
63
+ cin>>d;
64
+ if (d!=-1 ){
65
+ temp->right = new node (d);
66
+ q.push (temp->right );
67
+ }
68
+
69
+ }
70
+ return root;
71
+ }
72
+ void topView (node* root){
73
+ queue<node*> q;
74
+ map<int ,int > m;
75
+ int hd = 0 ;
76
+ root->hd = hd;
77
+ q.push (root);
78
+ while (!q.empty ()){
79
+ node* temp = q.front ();
80
+ q.pop ();
81
+ hd = temp->hd ;
82
+ if (m[hd]==0 ){
83
+ m[hd] = temp->data ;
84
+ }
85
+ if (temp->left ){
86
+ temp->left ->hd = hd - 1 ;
87
+ q.push (temp->left );
88
+ }
89
+ if (temp->right ){
90
+ temp->right ->hd = hd+1 ;
91
+ q.push (temp->right );
92
+ }
93
+ }
94
+
95
+ for (auto x: m){
96
+ cout<<x.second <<" " ;
97
+ }
98
+ }
99
+
100
+ int main () {
101
+ node * root = build ();
102
+ topView (root);
103
+ return 0 ;
104
+ }
You can’t perform that action at this time.
0 commit comments