-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathMaximum Width of Binary Tree.cpp
61 lines (43 loc) · 1.58 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
/*
Solution By Rahul Surana
***********************************
Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes),
where the null nodes between the end-nodes are also counted into the length calculation.
It is guaranteed that the answer will in the range of 32-bit signed integer.
*************************************/
#include<bits/stdc++.h>
/**
* 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) {
unsigned long long ans = 0;
queue<pair<TreeNode*,unsigned long long>> q;
q.push({root,1ULL});
while(!q.empty()){
int s = q.size();
ans = max(ans,q.back().second - q.front().second+1);
while(s--){
auto [x,y] = q.front();
q.pop();
if(!x) { continue; }
if(x->left)
q.push({x->left,y*2+1});
if(x->right)
q.push({x->right,y*2+2});
}
}
return ans;
}
};