-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
38 lines (32 loc) · 1.07 KB
/
solution.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
/**
* 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 == NULL) return 0;
queue<pair<TreeNode*, unsigned>> q;
q.push({ root, 1 });
unsigned answer = 1;
while(!q.empty()) {
answer = max(answer, q.back().second - q.front().second + 1);
int size = q.size();
while(size-- > 0) {
TreeNode* temp = q.front().first;
unsigned id = q.front().second;
q.pop();
if(temp->left) q.push({ temp->left, 2 * id });
if(temp->right) q.push({ temp->right, 2 * id + 1 });
}
}
return answer;
}
};