解题思路
用pos2与pos2+1来保存节点的位置,在层序遍历中,每一层第一个遍历到的节点就是该层的左边界
然后通过res = max(res,pos-l+1)来求最长宽度(不用去寻找右边界)
利用unsigned long long来保存每个节点的位置防止越界
代码
class Solution {
public:
queue<pair<unsigned long long,TreeNode*>> q;
int widthOfBinaryTree(TreeNode* root) {
unsigned long long res = 0;
if(root == nullptr) return res;
q.push({1,root});
while(q.size()){
int len = q.size();
unsigned long long l = -1;
while(len--){
unsigned long long pos = q.front().first;
TreeNode* cur = q.front().second;
q.pop();
if(l == -1) l = pos;
if(cur->left) q.push({pos*2,cur->left});
if(cur->right) q.push({pos*2+1,cur->right});
res = max(res,pos-l+1);
}
}
return res;
}
};