Skip to content

Commit 26abf35

Browse files
committed
Vertical Width of a Binary Tree
1 parent 8a32039 commit 26abf35

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
2+
//Initial Template for C++
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
struct Node
6+
{
7+
int data;
8+
struct Node* left;
9+
struct Node* right;
10+
11+
Node(int x){
12+
data = x;
13+
left = right = NULL;
14+
}
15+
};
16+
// your task is to complete this functionh
17+
// function should return the width of the tree
18+
int verticalWidth(Node* root);
19+
int main()
20+
{
21+
int t;
22+
struct Node *child;
23+
scanf("%d", &t);
24+
while (t--)
25+
{
26+
map<int, Node*> m;
27+
int n;
28+
scanf("%d",&n);
29+
struct Node *root = NULL;
30+
while (n--)
31+
{
32+
Node *parent;
33+
char lr;
34+
int n1, n2;
35+
scanf("%d %d %c", &n1, &n2, &lr);
36+
if (m.find(n1) == m.end())
37+
{
38+
parent = new Node(n1);
39+
m[n1] = parent;
40+
if (root == NULL)
41+
root = parent;
42+
}
43+
else
44+
parent = m[n1];
45+
child = new Node(n2);
46+
if (lr == 'L')
47+
parent->left = child;
48+
else
49+
parent->right = child;
50+
m[n2] = child;
51+
}
52+
cout<<verticalWidth(root)<<endl;
53+
}
54+
return 0;
55+
}
56+
57+
58+
//Position this line where user code will be pasted.
59+
60+
/*This is a function problem.You only need to complete the function given below*/
61+
//User function Template for C++
62+
/*Structure of node of binary tree is as
63+
struct Node
64+
{
65+
int data;
66+
struct Node* left;
67+
struct Node* right;
68+
69+
Node(int x){
70+
data = x;
71+
left = right = NULL;
72+
}
73+
};
74+
*/
75+
// your task is to complete this functionh
76+
// function should return the width of the tree
77+
78+
void verwid(Node* root, int *mindis, int *maxdis, int current_distance)
79+
{
80+
if(root == NULL)
81+
return;
82+
if(current_distance < *mindis)
83+
*mindis -=1;
84+
if(current_distance > *maxdis)
85+
*maxdis +=1;
86+
if(root->left)
87+
verwid(root->left,mindis,maxdis,current_distance-1);
88+
if(root->right)
89+
verwid(root->right,mindis,maxdis, current_distance+1);
90+
}
91+
92+
int verticalWidth(Node* root)
93+
{
94+
if(root == NULL)
95+
return 0;
96+
int mindis=0,maxdis=0;
97+
verwid(root,&mindis,&maxdis,0);
98+
return (maxdis - mindis +1);
99+
// Code here
100+
}

0 commit comments

Comments
 (0)