-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathMaximum Width of Binary Tree.cpp
104 lines (95 loc) · 2.4 KB
/
Maximum Width of Binary 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<bits/stdc++.h>
#define ll int
using namespace std;
// ***********************************************************
// Following is the TreeNode class structure:
template <typename T>
class TreeNode {
public:
T val;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val) {
this->val = val;
left = NULL;
right = NULL;
}
};
// ***********************************************************
int widthOfBinaryTree(TreeNode<ll>* root) {
if(root==nullptr)
return 0;
queue<pair<TreeNode<ll>*,ll>> q;
q.push({root,0});
q.push({nullptr,-1});
ll ans = 0;
ll mini = 0, maxi = 0;
ll op = 0;
ll flag = 1;
while(q.size())
{
auto cur = q.front();
q.pop();
if(cur.first==nullptr)
{
if(q.size()==0)
break;
q.push({nullptr,-1});
flag = 1;
continue;
}
if(flag)
op = cur.second, flag = 0;
cur.second-=op;
mini = min(mini,cur.second);
maxi = max(maxi,cur.second);
if(cur.first->left)
q.push({cur.first->left, 2ll*cur.second+1});
if(cur.first->right)
q.push({cur.first->right, 2ll*cur.second+2});
ans = max(ans,maxi-mini+1);
}
return ans;
}
TreeNode<ll>* createTree()
{
queue<TreeNode<ll>*> q;
TreeNode<ll> *root = nullptr;
ll val;
cout<<"Enter value of root - "<<endl;
cin>>val;
root = new TreeNode<ll>(val);
q.push(root);
while(q.size())
{
auto cur = q.front();
q.pop();
ll lef,rig;
cout<<"Enter left child of "<<cur->val<<endl;
cin>>lef;
cout<<"Enter right child of "<<cur->val<<endl;
cin>>rig;
if(lef==-1)
cur->left = nullptr;
else
{
TreeNode<ll> *l = new TreeNode<ll>(lef);
cur->left = l;
q.push(l);
}
if(rig==-1)
cur->right = nullptr;
else
{
TreeNode<ll> *r = new TreeNode<ll>(rig);
cur->right = r;
q.push(r);
}
}
return root;
}
int main()
{
TreeNode<ll> *root = createTree();
cout<<widthOfBinaryTree(root);
}