File tree Expand file tree Collapse file tree 1 file changed +97
-0
lines changed
Expand file tree Collapse file tree 1 file changed +97
-0
lines changed Original file line number Diff line number Diff line change 1+ {
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+ /* A binary tree node has data, pointer to left child
5+ and a pointer to right child */
6+ struct Node
7+ {
8+ int data;
9+ struct Node * left;
10+ struct Node * right;
11+ Node (int x){
12+ data = x;
13+ left = right = NULL ;
14+ }
15+ };
16+ void topView (struct Node *root);
17+ /* Driver program to test size function*/
18+ int main ()
19+ {
20+ int t;
21+ struct Node *child;
22+ cin >> t;
23+ while (t--)
24+ {
25+ map<int , Node*> m;
26+ int n;
27+ cin >> n;
28+ struct Node *root = NULL ;
29+ while (n--)
30+ {
31+ Node *parent;
32+ char lr;
33+ int n1, n2;
34+ scanf (" %d %d %c" , &n1, &n2, &lr);
35+ if (m.find (n1) == m.end ())
36+ {
37+ parent = new Node (n1);
38+ m[n1] = parent;
39+ if (root == NULL )
40+ root = parent;
41+ }
42+ else
43+ parent = m[n1];
44+ child = new Node (n2);
45+ if (lr == ' L' )
46+ parent->left = child;
47+ else
48+ parent->right = child;
49+ m[n2] = child;
50+ }
51+ topView (root);
52+ cout << endl;
53+ }
54+ return 0 ;
55+ }
56+
57+ }
58+ /* This is a function problem.You only need to complete the function given below*/
59+ // Structure of binary tree
60+ /* struct Node
61+ struct Node
62+ {
63+ int data;
64+ struct Node* left;
65+ struct Node* right;
66+
67+ Node(int x){
68+ data = x;
69+ left = right = NULL;
70+ }
71+ };*/
72+ // function should print the topView of the binary tree
73+ void topView (struct Node *root)
74+ {
75+ // Your code here
76+
77+ map<int , int > m; // node->data, vertical_dist
78+ queue<pair<Node*, int >> q; // node, verticaL_dist
79+ q.push ({root, 0 });
80+ while (!q.empty ()){
81+ pair<Node*, int > top = q.front ();
82+ Node* c = top.first ;
83+ int hd = top.second ;
84+ q.pop ();
85+ if (m.find (hd) == m.end ()){
86+ // v.push_back(c->data);
87+ m[hd] = c->data ;
88+ }
89+ if (c->left )
90+ q.push ({c->left , hd - 1 });
91+
92+ if (c->right )
93+ q.push ({c->right , hd + 1 });
94+ }
95+ for (auto i: m)
96+ cout<<i.second <<" " ;
97+ }
You can’t perform that action at this time.
0 commit comments