-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtopview.cpp
99 lines (76 loc) · 1.62 KB
/
topview.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<iostream>
#include<queue>
//#include<pair>
#include<unordered_map>
using namespace std;
struct node{
int data;
node *left;
node *right;
node(int k)
{
data=k;
left=NULL;
right=NULL;
}
};
node* addnode()
{
queue<node*> q;
int n,k;
node* root;
cin>>n; //n defines the number of nodes
while(n--)
{
cin>>k; //data value of the node
node* a = new node(k);
if(!q.empty())
{
if(q.front()->left==NULL)
{
q.front()->left=a;
}
else if(q.front()->right==NULL)
{
q.front()->right=a;
q.pop();
}
}
else
{
root=a;
}
q.push(a);
}
return root;
}
void topView(struct node* root)
{
if (root == NULL)
return;
unordered_map<int, int> m;
// m.first contains the horizontal distance and second contains the value printed corresponding to the distance
queue<pair<node*, int> > q;
//q.second contains the horizontal value
q.push(make_pair(root, 0));
while (!q.empty()) {
pair<node*, int> p = q.front();
node* n = p.first;
int val = p.second;
q.pop();
if (m.find(val) == m.end()) {
m[val] = n->data;
printf("%d ", n->data);
}
if (n->left != NULL)
q.push(make_pair(n->left, val - 1));
if (n->right != NULL)
q.push(make_pair(n->right, val + 1));
}
}
int main()
{
node * root = addnode();
topView(root);
return 0;
}