-
Notifications
You must be signed in to change notification settings - Fork 8
/
bottom-view-of-a-tree.cpp
65 lines (63 loc) · 1.38 KB
/
bottom-view-of-a-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
60
61
62
63
64
65
//Bottom View of a Tree
#include <bits/stdc++.h>
using namespace std;
#define faster ios_base::sync_with_stdio(false);cin.tie(NULL);
typedef long long int ll;
#define mkp make_pair
struct Node{
ll data;
ll hd;
Node * left,*right;
Node(ll val)
{
data=val;
hd=INT_MAX;
left=NULL;
right=NULL;
}
};
void bottomView(Node* root)
{
if(root==NULL)
return;
map<ll,ll> mp;
ll hd=0;
queue<Node*> q;
q.push(root);
root->hd=0;
while(!q.empty())
{
Node* temp=q.front();
q.pop();
hd=temp->hd;
mp[hd]=temp->data;
if(temp->left!=NULL)
{
temp->left->hd=hd-1;
q.push(temp->left);
}
if(temp->right!=NULL)
{
temp->right->hd=hd+1;
q.push(temp->right);
}
}
map<ll,ll>::iterator it;
for(it=mp.begin();it!=mp.end();it++)
cout<<it->second<<" ";
}
int main()
{
faster
Node *root=new Node(20);
root->left=new Node(8);
root->right=new Node(22);
root->left->left=new Node(5);
root->left->right=new Node(3);
root->right->left=new Node(4);
root->right->right=new Node(25);
root->left->right->left=new Node(10);
root->left->right->right=new Node(14);
bottomView(root);
return 0;
}