-
Notifications
You must be signed in to change notification settings - Fork 3
/
bottomViewOfTree.cpp
72 lines (53 loc) · 1.33 KB
/
bottomViewOfTree.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
// BFS
vector <int> bottomView(Node *root)
{
if(!root)
return vector<int> ();
map<int, int> mp;
queue<pair<Node*, int>> q;
q.push({root, 0});
while(!q.empty()){
auto temp = q.front();
q.pop();
Node* node = temp.first;
int hd = temp.second;
mp[hd] = node -> data;
if(node -> left)
q.push({node -> left, hd - 1});
if(node -> right)
q.push({node -> right, hd + 1});
}
vector<int> ans;
for(auto x : mp)
ans.push_back(x.second);
return ans;
}
// DFS segmentation fault
map<int, pair<int, int>> mp;
void solve(Node *root, int curlevel, int hd){
if(!root)
return;
if(mp.find(hd) == mp.end()){
mp[hd] = {root -> data, curlevel};
}
else{
pair<int, int> p = mp[hd];
if(p.second <= curlevel){
mp[hd].first = root -> data;
mp[hd].second = curlevel;
}
}
solve(root -> left, curlevel + 1, hd - 1);
solve(root -> right, curlevel + 1, hd + 1);
}
vector <int> bottomView(Node *root)
{
if(!root)
return vector<int> ();
solve(root, 0, 0);
vector<int> ans;
for(auto x : mp){
ans.push_back(x.second.first);
}
return ans;
}