-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbottom_view.cpp
More file actions
68 lines (64 loc) · 1.51 KB
/
Copy pathbottom_view.cpp
File metadata and controls
68 lines (64 loc) · 1.51 KB
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
// recursive approach to bottom view of tree
void bottom_view_helper(Node* root, map<int,pair<Node*,int>> &m,int depth,int vd)
{
if(root == NULL)
return;
if(m.count(vd) == 0)
m[vd]=make_pair(root,depth);
else if(m[vd].second <= depth)
m[vd]=make_pair(root,depth);
bottom_view_helper(root -> left, m,depth + 1,vd - 1);
bottom_view_helper(root -> right, m, depth + 1, vd + 1);
}
vector <int> bottomView(Node *root)
{
map<int,pair<Node*,int>> m;
bottom_view_helper(root,m,0,0);
vector<int> v;
auto it = m.begin();
while(it != m.end())
{
Node *temp=(it->second).first;
v.push_back(temp -> data);
it++;
}
return v;
}
//iterative approach
vector <int> bottomView(Node *root)
{
vector<int> v;
v.push_back(0);
if(root == NULL)
return v;
v.pop_back();
queue<pair<Node*,int>>q;
q.push(make_pair(root,0));
int vd = 0;
int count_size = 0;
map<int,int> m;
while(!q.empty())
{
count_size = q.size();
while(count_size)
{
pair<Node*,int> temp = q.front();
q.pop();
vd = temp.second;
Node *node = temp.first;
m[vd] = node -> data;
if(node -> left)
q.push(make_pair(node -> left , vd - 1));
if(node -> right)
q.push(make_pair(node -> right , vd + 1));
count_size--;
}
}
auto it = m.begin();
while(it != m.end())
{
v.push_back(it -> second);
it++;
}
return v;
}