题目
Leetcode 662. 二叉树最大宽度
代码(9.30 首刷看解析)
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
unsigned long long res = 1;
using pr = pair<TreeNode*, unsigned long long>;
vector<pr> arr;
arr.emplace_back(root, 1);
while(!arr.empty()) {
vector<pr> tmp;
for(auto& [node, index] : arr) {
if(node->left)
tmp.emplace_back(node->left, index*2);
if(node->right)
tmp.emplace_back(node->right, index*2+1);
}
res = max(res, arr.back().second - arr[0].second + 1);
arr = move(tmp);
}
return res;
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21