forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum_Width_of_Binary_Tree.cpp
40 lines (40 loc) · 1.19 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if(!root) return 0;
queue<pair<TreeNode*, pair<int, int>>> Q;
int level = -1;
int maxWidth = 0;
int minIndx = 1, maxIndx = 1;
Q.push({root, {0, 1}});
while(!Q.empty()) {
TreeNode* curr = Q.front().first;
int currLevel = Q.front().second.first;
int currIndx = Q.front().second.second;
Q.pop();
if(currLevel != level) {
level = currLevel;
maxWidth = max(maxWidth, maxIndx - minIndx + 1);
minIndx = currIndx;
}
maxIndx = currIndx;
if(curr->left) {
Q.push({curr->left, {currLevel + 1, currIndx << 1}});
}
if(curr->right) {
Q.push({curr->right, {currLevel + 1, ((currIndx << 1) | 1)}});
}
}
maxWidth = max(maxWidth, maxIndx - minIndx + 1);
return maxWidth;
}
};