LeetCode 662. 二叉树最大宽度
这道题比较坑,如果你直接按左子树,2i,右子树 2i+1,这样存的话数据会溢出。所以你需要简单操作一下。
if(a->t->left) q.push(new node(a->t->left,(a->width-start+1)*2));
if(a->t->right) q.push(new node(a->t->right,(a->width-start+1)*2+1));
struct node{
TreeNode *t;
long long width;
node(TreeNode *_t,long long _width)
{
t=_t;
width=_width;
}
};
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
queue<node *> q;
q.push(new node(root,1));
long long Max=-100000000000;
while(!q.empty())
{
node * l=q.front();
node * r=q.back();
Max=max((r->width - l->width)+1,Max);
int len=q.size();
long long start=l->width;
for(int i=0;i<len;i++)
{
node *a=q.front();
q.pop();
if(a->t->left) q.push(new node(a->t->left,(a->width-start+1)*2));
if(a->t->right) q.push(new node(a->t->right,(a->width-start+1)*2+1));
}
}
return Max;
}
};