-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bottom View of Binary Tree GFG.cpp
55 lines (51 loc) · 1.36 KB
/
Bottom View of Binary Tree GFG.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
// tc=o(n)
// sc=o(n)
class Solution {
public:
vector <int> bottomView(Node *root) {
if(!root) return {};
vector<int> res;
map<int,int> mp;
queue<pair<Node*,int>> que;
que.push({root,0});
while(!que.empty()){
Node* node=que.front().first;
int line=que.front().second;
mp[line]=node->data;
que.pop();
if(node->left) que.push({node->left,line-1});
if(node->right) que.push({node->right,line+1});
}
for(auto i: mp){
res.push_back(i.second);
}
return res;
}
};
// tc=o(n)
// sc=o(n)
class Solution {
public:
vector <int> bottomView(Node *root) {
if(!root) return {};
vector<int> res;
unordered_map<int,int> map;
queue<pair<Node*,int>> que;
int maxi=0, mini=0;
que.push({root,0});
while(!que.empty()){
Node* node=que.front().first;
int line=que.front().second;
map[line]=node->data;
maxi=max(maxi,line);
mini=min(mini,line);
que.pop();
if(node->left) que.push({node->left,line-1});
if(node->right) que.push({node->right,line+1});
}
for(int i=mini;i<=maxi;i++){
res.push_back(map[i]);
}
return res;
}
};