forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum_width_of_binary_tree.cpp
More file actions
86 lines (78 loc) · 1.77 KB
/
maximum_width_of_binary_tree.cpp
File metadata and controls
86 lines (78 loc) · 1.77 KB
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
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
class BinaryTree
{
int idx = -1;
public:
Node *BuildTree(int arr[])
{
idx++;
if (arr[idx] == -1)
{
return NULL;
}
Node *newNode = new Node(arr[idx]);
newNode->left = BuildTree(arr);
newNode->right = BuildTree(arr);
return newNode;
}
};
int max_width(Node* root){
if(root == NULL){
return 0;
}
queue<pair<Node* , int>> q;
q.push({root, 0});
int ans = 0;
while(!q.empty()){
// Node* newNode = q.front().first;
int qsize = q.size();
int subtract_val = q.front().second;
int first, last;
for(int i=0; i<qsize; i++){
pair<Node*, int> p = q.front();
int cur_id = p.second - subtract_val;
q.pop();
if(i==0){
first = cur_id;
}
if(i==qsize-1){
last = cur_id;
}
if(p.first->left!=NULL){
int idx = 2*(p.second - subtract_val) +1;
q.push({p.first->left, idx});
}
if(p.first->right!=NULL){
int idx = 2*(p.second - subtract_val) +2;
q.push({p.first->right, idx});
}
}
ans = max(ans, last-first+1);
}
return ans;
}
int main()
{
int nodes[] = {1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1};
BinaryTree *tree = new BinaryTree();
Node *root = tree->BuildTree(nodes);
int Max_width = max_width(root);
cout<<Max_width;
return 0;
}