Skip to content

Commit 3069e91

Browse files
Added bottom viewq
1 parent 258feb0 commit 3069e91

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

amazon/bottom_view_binary_tree.cpp

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
{
2+
// C++ Program to print Bottom View of Binary Tree
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
// Tree node class
6+
struct Node
7+
{
8+
int data; //data of the node
9+
Node *left, *right; //left and right references
10+
// Constructor of tree node
11+
Node(int key)
12+
{
13+
data = key;
14+
left = right = NULL;
15+
}
16+
};
17+
// Method that prints the bottom view.
18+
void bottomView(Node *root);
19+
/* Driver program to test size function*/
20+
int main()
21+
{
22+
int t;
23+
struct Node *child;
24+
scanf("%d
25+
", &t);
26+
while (t--)
27+
{
28+
map<int, Node*> m;
29+
int n;
30+
scanf("%d
31+
",&n);
32+
struct Node *root = NULL;
33+
while (n--)
34+
{
35+
Node *parent;
36+
char lr;
37+
int n1, n2;
38+
scanf("%d %d %c", &n1, &n2, &lr);
39+
if (m.find(n1) == m.end())
40+
{
41+
parent = new Node(n1);
42+
m[n1] = parent;
43+
if (root == NULL)
44+
root = parent;
45+
}
46+
else
47+
parent = m[n1];
48+
child = new Node(n2);
49+
if (lr == 'L')
50+
parent->left = child;
51+
else
52+
parent->right = child;
53+
m[n2] = child;
54+
}
55+
bottomView(root);
56+
cout << endl;
57+
}
58+
return 0;
59+
}
60+
61+
}
62+
/*This is a function problem.You only need to complete the function given below*/
63+
/* Tree node class
64+
struct Node
65+
{
66+
int data; //data of the node
67+
Node *left, *right; //left and right references
68+
// Constructor of tree node
69+
Node(int key)
70+
{
71+
data = key;
72+
left = right = NULL;
73+
}
74+
}; */
75+
// Method that prints the bottom view.
76+
void bottomView(Node *root)
77+
{
78+
// Your Code Here
79+
80+
if(root){
81+
map<int, int> mp;
82+
queue<pair<Node*, int>> q;
83+
int hd = 0;
84+
q.push({root, hd});
85+
86+
while(!q.empty()){
87+
pair<Node*, int> cp = q.front();
88+
Node *currNode = cp.first;
89+
hd = cp.second;
90+
q.pop();
91+
92+
mp[hd] = currNode->data;
93+
if(currNode->left != NULL)
94+
q.push({currNode->left, hd - 1});
95+
if(currNode->right != NULL)
96+
q.push({currNode->right, hd + 1});
97+
}
98+
for(auto it = mp.begin(); it != mp.end(); it++){
99+
cout<<it->second<<" ";
100+
}
101+
}
102+
else
103+
return;
104+
}

0 commit comments

Comments
 (0)