Skip to content

Commit a42e1d8

Browse files
committed
Top View of Binary Tree
1 parent 913c8c2 commit a42e1d8

File tree

1 file changed

+39
-33
lines changed

1 file changed

+39
-33
lines changed

Tree/Top View of Binary Tree.cpp

Lines changed: 39 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,19 @@ struct Node
1414
left = right = NULL;
1515
}
1616
};
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);
2718
/* Driver program to test size function*/
2819
int main()
2920
{
3021
int t;
31-
scanf("%d
32-
", &t);
22+
struct Node *child;
23+
scanf("%d", &t);
3324
while (t--)
3425
{
3526
map<int, Node*> m;
3627
int n;
3728
scanf("%d",&n);
3829
struct Node *root = NULL;
39-
struct Node *child;
4030
while (n--)
4131
{
4232
Node *parent;
@@ -59,17 +49,19 @@ int main()
5949
parent->right = child;
6050
m[n2] = child;
6151
}
62-
cout << height(root) << endl;
52+
topView(root);
53+
cout << endl;
6354
}
6455
return 0;
6556
}
6657

6758

6859
/*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
7062
struct Node
7163
{
72-
int data;
64+
int data, hd;
7365
struct Node* left;
7466
struct Node* right;
7567
@@ -78,23 +70,37 @@ struct Node
7870
left = right = NULL;
7971
}
8072
};*/
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)
8375
{
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});
9083

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));
97101

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

Comments
 (0)