Skip to content

Commit b850ff4

Browse files
committed
Maximum Width of Tree
1 parent 656cf5f commit b850ff4

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed

Tree/Maximum Width of Tree.cpp

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
/* A binary tree node has data, pointer to left child
5+
and a pointer to right child */
6+
struct Node
7+
{
8+
int data;
9+
struct Node* left;
10+
struct Node* right;
11+
12+
Node(int x){
13+
data = x;
14+
left = right = NULL;
15+
}
16+
};
17+
/* Function to get the maximum width of a binary tree*/
18+
int getMaxWidth(Node* root);
19+
/* Driver program to test size function*/
20+
int main()
21+
{
22+
int t;
23+
struct Node *child;
24+
scanf("%d", &t);
25+
while (t--)
26+
{
27+
map<int, Node*> m;
28+
int n;
29+
scanf("%d",&n);
30+
struct Node *root = NULL;
31+
while (n--)
32+
{
33+
Node *parent;
34+
char lr;
35+
int n1, n2;
36+
scanf("%d %d %c", &n1, &n2, &lr);
37+
if (m.find(n1) == m.end())
38+
{
39+
parent = new Node(n1);
40+
m[n1] = parent;
41+
if (root == NULL)
42+
root = parent;
43+
}
44+
else
45+
parent = m[n1];
46+
child = new Node(n2);
47+
if (lr == 'L')
48+
parent->left = child;
49+
else
50+
parent->right = child;
51+
m[n2] = child;
52+
}
53+
cout << getMaxWidth(root) << endl;
54+
}
55+
return 0;
56+
}
57+
58+
59+
/*This is a function problem.You only need to complete the function given below*/
60+
/* Structure of a Binary Tree
61+
struct Node
62+
{
63+
int data;
64+
struct Node* left;
65+
struct Node* right;
66+
67+
Node(int x){
68+
data = x;
69+
left = right = NULL;
70+
}
71+
};
72+
*/
73+
/* Function to get the maximum width of a binary tree*/
74+
int getMaxWidth(Node* root)
75+
{
76+
if(root == NULL)
77+
return 0;
78+
79+
queue<Node*> q;
80+
q.push(root);
81+
int size = q.size();
82+
int result = size;
83+
while(!q.empty())
84+
{
85+
size = q.size();
86+
while(size>0)
87+
{
88+
Node* temp = q.front();
89+
q.pop();
90+
if(temp->left)
91+
q.push(temp->left);
92+
if(temp->right)
93+
q.push(temp->right);
94+
size--;
95+
96+
}
97+
if(result< q.size())
98+
result = q.size();
99+
}
100+
return result;
101+
// Your code here
102+
}
103+
104+
/*Input:
105+
2
106+
2
107+
1 2 R 1 3 L
108+
4
109+
10 20 L 10 30 R 20 40 L 20 60 R
110+
111+
Output:
112+
2
113+
2 */

0 commit comments

Comments
 (0)