-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbottom_view_of_binary_tree.cpp
59 lines (51 loc) · 1.07 KB
/
bottom_view_of_binary_tree.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
#include<bits/stdc++.h>
using namespace std;
// 10
// / \
// 20 30
// / \
// 40 50
struct Node{
Node *right;
Node *left;
int data;
Node(int key){
data = key;
right = left = NULL;
}
};
// TC = O(n)
vector <int> bottomView(Node *root) {
queue<pair<Node*,int>>q;
q.push({root,0});
map<int,int>mp;
while(q.size()){
auto curr = q.front();
q.pop();
Node *node = curr.first;
int x = curr.second;
mp[x] = node->data;
if(node->left){
q.push({node->left,x-1});
}
if(node->right){
q.push({node->right,x+1});
}
}
vector<int>ans;
for(auto x:mp){
ans.push_back(x.second);
}
return ans;
}
int main() {
struct Node *root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->right->left = new Node(40);
root->right->right = new Node(50);
vector<int>v = bottomView(root);
for(int x:v) cout<<x<<" ";
cout<<endl;
return 0;
}