-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCS_43_BottomViewOfBT.cpp
100 lines (87 loc) · 2.01 KB
/
CS_43_BottomViewOfBT.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
100
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class TreeNode
{
public:
T data;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
~TreeNode()
{
if (left)
delete left;
if (right)
delete right;
}
};
vector<int> bottomView(TreeNode<int> *root)
{
map<int, int> hdToNode;
queue<pair<TreeNode<int> *, int>> q;
q.push({root, 0});
while (!q.empty())
{
pair<TreeNode<int> *, int> temp = q.front();
q.pop();
TreeNode<int> *frontNode = temp.first;
int hd = temp.second;
hdToNode[hd] = frontNode->data;
// children
if (frontNode->left != NULL)
{
q.push({frontNode->left, hd - 1});
}
if (frontNode->right != NULL)
{
q.push({frontNode->right, hd + 1});
}
}
vector<int> ans;
for (auto i : hdToNode)
{
ans.push_back(i.second);
}
return ans;
}
int main()
{
// considering tree as
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
// \ \
// 8 9
// /
// 10
// \
// 11
TreeNode<int> *root = new TreeNode<int>(1);
root->left = new TreeNode<int>(2);
root->right = new TreeNode<int>(3);
root->left->left = new TreeNode<int>(4);
root->left->right = new TreeNode<int>(5);
root->right->left = new TreeNode<int>(6);
root->right->right = new TreeNode<int>(7);
root->left->right->right = new TreeNode<int>(8);
root->right->right->right = new TreeNode<int>(9);
root->right->right->right->left = new TreeNode<int>(10);
root->right->right->right->left->right = new TreeNode<int>(11);
vector<int> ans = bottomView(root);
cout << "Bottom view of the tree is : ";
for (auto i : ans)
{
cout << i << " ";
}
cout << endl;
delete root;
return 0;
}