LeetCode 662. 二叉树最大宽度

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;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值