-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtop_view_of_binary_tree.cpp
47 lines (38 loc) · 1.46 KB
/
top_view_of_binary_tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// problem link: https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1
// just like in right and left view binary tree we did level order traversal
// similarly we will do vertical order traversal for top and bottom view
// refer vertical sum and vertical traversal questions
void verticalTraversal(Node* root, map<int, int> &mp)
{
queue<pair<Node *, int>> q; // node as key and horizontal dist from root as value
q.push({root, 0});
while(q.size() != 0)
{
int count = q.size();
for(int i=0; i<count; i++)
{
auto top = q.front();
Node* curr = top.first;
int horizontalDist = top.second;
if(mp.find(horizontalDist) == mp.end())
{
//cout<<horizontalDist<<endl;
mp[horizontalDist] = curr->data;
//cout<<"hi"<<mp[horizontalDist]<<endl;
}
q.pop();
if(curr -> left) q.push({curr->left, horizontalDist - 1});
if(curr -> right) q.push({curr->right, horizontalDist + 1});
}
}
}
vector<int> topView(Node *root)
{
map<int, int> mp;
verticalTraversal(root, mp);
vector <int> ans;
for(auto i: mp){
ans.push_back(i.second);
}
return ans;
}