@@ -14,29 +14,19 @@ struct Node
14
14
left = right = NULL ;
15
15
}
16
16
};
17
- /* Computes the number of nodes in a tree. */
18
- int height (struct Node * node);
19
- void inorder (Node *root)
20
- {
21
- if (root == NULL )
22
- return ;
23
- inorder (root->left );
24
- cout << root->data << " " ;
25
- inorder (root->right );
26
- }
17
+ void topView (Node *root);
27
18
/* Driver program to test size function*/
28
19
int main ()
29
20
{
30
21
int t;
31
- scanf ( " %d
32
- " , &t);
22
+ struct Node *child;
23
+ scanf ( " %d " , &t);
33
24
while (t--)
34
25
{
35
26
map<int , Node*> m;
36
27
int n;
37
28
scanf (" %d" ,&n);
38
29
struct Node *root = NULL ;
39
- struct Node *child;
40
30
while (n--)
41
31
{
42
32
Node *parent;
@@ -59,17 +49,19 @@ int main()
59
49
parent->right = child;
60
50
m[n2] = child;
61
51
}
62
- cout << height (root) << endl;
52
+ topView (root);
53
+ cout << endl;
63
54
}
64
55
return 0 ;
65
56
}
66
57
67
58
68
59
/* This is a function problem.You only need to complete the function given below*/
69
- /* Tree node structure used in the program
60
+ // Structure of binary tree
61
+ /* struct Node
70
62
struct Node
71
63
{
72
- int data;
64
+ int data, hd ;
73
65
struct Node* left;
74
66
struct Node* right;
75
67
@@ -78,23 +70,37 @@ struct Node
78
70
left = right = NULL;
79
71
}
80
72
};*/
81
- /* Computes the height of binary tree with given root. */
82
- int height (Node* node )
73
+ // function should print the topView of the binary tree
74
+ void topView (Node *root )
83
75
{
84
- if (node == NULL )
85
- return 0 ;
86
- return (max (height (node->left ),height (node->right ))+1 );
87
- // Your code here
88
- }
89
-
76
+
77
+ if (root == NULL )
78
+ return ;
79
+
80
+ unordered_set<int > us;
81
+ queue<pair<Node *,int >> q;
82
+ q.push ({root,0 });
90
83
91
- /* Input:
92
- 2
93
- 2
94
- 1 2 L 1 3 R
95
- 4
96
- 10 20 L 10 30 R 20 40 L 20 60 R
84
+ while (!q.empty ())
85
+ {
86
+ pair<Node*, int > tp = q.front ();
87
+ Node* temp = tp.first ;
88
+ // Node* temp = q.front.first;
89
+ int hd = tp.second ; // q.front.second;
90
+ q.pop ();
91
+ if (us.find (hd) == us.end ())
92
+ {
93
+ cout<<temp->data <<" " ;
94
+ us.insert (hd);
95
+ }
96
+ if (temp->left )
97
+ q.push (make_pair (temp->left ,hd-1 ));
98
+
99
+ if (temp->right )
100
+ q.push (make_pair (temp->right ,hd+1 ));
97
101
98
- Output:
99
- 2
100
- 3 */
102
+ }
103
+ // for(auto itterator = us.begin();itterator!=us.end;itterator++)
104
+
105
+ // Your code here
106
+ }
0 commit comments