forked from diwakar1593/CPP-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
max_width_binary_tree.cpp
84 lines (67 loc) · 1.45 KB
/
max_width_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
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode * left;
TreeNode * right;
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};
int maxWidth(TreeNode *root)
{
if (!root) return 0;
int maxWidth = 0;
queue<pair<TreeNode*, int>> q;
q.push({root, 1});
while (!q.empty())
{
int leftmost = q.front().second;
int rightmost = leftmost;
int levelSize = q.size();
for (int i = 0; i < levelSize; i++)
{
TreeNode *node = q.front().first;
int position = q.front().second;
q.pop();
rightmost = position;
if (node->left) q.push({ node->left, position *2 });
if (node->right) q.push({ node->right, position *2 + 1});
}
maxWidth = max(maxWidth, rightmost-leftmost+1);
}
return maxWidth;
}
int main()
{
TreeNode *root = nullptr;
cout<<"Enter the values of the binary tree nodes (-1 for empty node) : "<<endl;
int value;
cin>>value;
if (value!=-1)
{
root = new TreeNode(value);
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty())
{
TreeNode *current = nodes.front();
nodes.pop();
int leftValue, rightValue;
cin>>leftValue>>rightValue;
if (leftValue!=-1)
{
current->left = new TreeNode(leftValue);
nodes.push(current->left);
}
if (rightValue!=-1)
{
current->right = new TreeNode(rightValue);
nodes.push(current->right);
}
}
}
int result = maxWidth(root);
cout<<"Maximum Width : "<<result<<endl;
return 0;
}