-
Notifications
You must be signed in to change notification settings - Fork 72
/
top_view_bst.cpp
69 lines (55 loc) · 1.05 KB
/
top_view_bst.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
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node* left;
Node* right;
int hd;
int data;
};
Node* newNode(int key)
{
Node* node = new Node();
node->left = node->right = NULL;
node->data = key;
return node;
}
void topview(Node* root)
{
if (root == NULL)
return;
queue<Node*> q;
map<int, int> m;
int hd = 0;
root->hd = hd;
q.push(root);
cout << "The top view of the tree is : \n";
while (q.size()) {
hd = root->hd;
if (m.count(hd) == 0)
m[hd] = root->data;
if (root->left) {
root->left->hd = hd - 1;
q.push(root->left);
}
if (root->right) {
root->right->hd = hd + 1;
q.push(root->right);
}
q.pop();
root = q.front();
}
for (auto i = m.begin(); i != m.end(); i++) {
cout << i->second << " ";
}
}
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->left->right->right = newNode(5);
root->left->right->right->right = newNode(6);
cout << "Following are nodes in top view of Binary "
"Tree\n";
topview(root);
return 0;
}