forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum width of binary tree.cpp
42 lines (42 loc) · 1.27 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if(!root)
return 0;
int ans = 0;
queue<pair<TreeNode*,int>> q;
q.push({root,0});
while(!q.empty()){
int size=q.size();
int mini=q.front().second;
int first,last;
for(int itr = 0; itr<size;itr++)
{
long long int cur_id = q.front().second-mini;
TreeNode* temp = q.front().first;
q.pop();
if(itr==0)
first = cur_id;
if(itr==size-1)
last = cur_id;
if(temp->left)
q.push({temp->left,cur_id*2+1});
if(temp->right)
q.push({temp->right,cur_id*2+2});
}
ans = max(ans, (last-first+1));
}
return ans;
}
};