-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbottomViewOfABinaryTree.cpp
90 lines (87 loc) · 2.25 KB
/
bottomViewOfABinaryTree.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
// Implemented by Kritagya Kumra
#include <iostream>
#include <vector>
#include <queue>
#include <map>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
vector<int> bottomViewOfBinaryTree(node *root)
{
// First int is for the hd and then second for the int value
map<int, int> nodes;
queue<pair<node *, int>> q;
vector<int> ans;
if (root == NULL)
{
return ans;
}
q.push(make_pair(root, 0));
while (!q.empty())
{
pair<node *, int> temp = q.front();
q.pop();
node *frontNode = temp.first;
int hd = temp.second;
nodes[hd] = frontNode->data;
if (frontNode->left != NULL)
{
q.push(make_pair(frontNode->left, hd - 1));
}
if (frontNode->right != NULL)
{
q.push(make_pair(frontNode->right, hd + 1));
}
}
// Fetch all the elements from the nodes and store it into the ans array
for (auto i : nodes)
{
ans.push_back(i.second);
}
return ans;
}
int main()
{
node *root1 = new node(10);
root1->left = new node(8);
root1->right = new node(2);
root1->left->left = new node(3);
root1->left->right = new node(5);
root1->right->left = new node(22);
root1->right->left->right = new node(12);
root1->right->left->right->left = new node(11);
// node *root1 = new node(20);
// root1->left = new node(8);
// root1->right = new node(12);
// root1->left->left = new node(3);
// root1->left->right = new node(5);
// root1->right->left = new node(2);
// root1->right->right = new node(10);
node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->left = new node(6);
root->right->right = new node(7);
root->right->left->right = new node(8);
root->right->right->right = new node(9);
// bool ans = isBalanced(root);
vector<int> ans = bottomViewOfBinaryTree(root);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
}
// Implemented by Kritagya Kumra