【剑斩OFFER】算法的暴力美学——leetCode 662 题:二叉树最大宽度

一、题目描述

二、算法原理

思路:使用队列实现层序遍历 + 让节点绑定一个下标 pair< TreeNode* , unsigned int>

例如:

计算左节点的下标的公式:父亲节点 * 2

计算右节点的下边的公式:父亲节点 * 2 + 1

第一层的宽度:1

第二层的宽度:3 - 2 + 1 = 2

第三层的宽度:6 - 4 + 1 = 3

故而最大的宽度位3

为什么使用 unsigned int 因为数值溢出了也不报错。

当使用 int 时,即使一个数溢出了:

此时这两个数其中一个溢出了,但是相减出来的值是正确的,不过这样编译器会报错,所以使用 unsigned int

三、代码实现

cpp 复制代码
/**
 * 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 == nullptr) return 0;
        queue<pair<TreeNode*,unsigned int>> que;//给每个节点绑定一个下标
        que.push({root,1});//让 root 绑定 1 下标
        unsigned int maxi = 0;//记录最大的宽度
        while(!que.empty())
        {
            int popnum = que.size();
            unsigned int l = que.front().second;//左边的节点的下标
            unsigned int r = 0;
            while(popnum--)
            {
                pair<TreeNode*,unsigned int> node = que.front();
                que.pop();
                unsigned int index = node.second;
                if(node.first->left != nullptr)
                {
                    que.push({node.first->left,2 * index});
                }
                if(node.first->right != nullptr)
                {
                    que.push({node.first->right,2 * index + 1});
                }
                if(popnum == 0) r = index;//最右节点的下标
            }
            maxi = max(maxi, r - l + 1);
        }
        return maxi;
    }
};
相关推荐
To_OC7 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
炸膛坦客8 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎8 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC8 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
Henry Zhu1238 小时前
C++中的特殊成员函数与智能指针
c++
delishcomcn9 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹9 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术10 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
_wyt00111 小时前
多重背包问题详解
c++·背包dp