-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtop_view of binary tree.cpp
More file actions
65 lines (55 loc) · 1.16 KB
/
top_view of binary tree.cpp
File metadata and controls
65 lines (55 loc) · 1.16 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//Top view in binary tree----set of nodes visible when the tree is viewed from the top
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
// here top view is 4 2 1 3 7
// iterative approach -- using queue
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
struct node{
int data;
struct node*left;
struct node*right;
// constructor
node(int val){
data=val;
left=right=NULL;
}
};
void topview(struct node*root){
queue<pair<struct node*, int>>q;
map<int,int>mp;
q.push({root,0});
while(!q.empty()){
struct node*curr=q.front().first;
int dist=q.front().second;
q.pop();
if(mp.count(dist)==0){
mp[dist]=curr->data;
}
if(curr->left!=NULL){
q.push({curr->left,dist-1});
}
if(curr->right!=NULL){
q.push({curr->right,dist+1});
}
}
for(auto i:mp){
cout<<i.second<<" ";
}
}
int main()
{
struct node*root= new node(1);
root->left= new node(2);
root->right=new node(7);
root->left->left=new node(3);
root->left->right= new node(4);
root->left->right->left= new node(5);
root->left->right->right= new node(6);
topview(root);
return 0;
}