【剑斩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;
    }
};
相关推荐
Trouvaille ~3 分钟前
【Linux】应用层协议设计实战(一):自定义协议与网络计算器
linux·运维·服务器·网络·c++·http·应用层协议
CSCN新手听安8 分钟前
【linux】高级IO,I/O多路转接之poll,接口和原理讲解,poll版本的TCP服务器
linux·运维·服务器·c++·计算机网络·高级io·poll
CSCN新手听安14 分钟前
【linux】网络基础(三)TCP服务端网络版本计算器的优化,Json的使用,服务器守护进程化daemon,重谈OSI七层模型
linux·服务器·网络·c++·tcp/ip·json
m0_7369191014 分钟前
C++中的委托构造函数
开发语言·c++·算法
小小小小王王王20 分钟前
洛谷-P1886 【模板】单调队列 / 滑动窗口
c++·算法
PPPPPaPeR.1 小时前
光学算法实战:深度解析镜片厚度对前后表面折射/反射的影响(纯Python实现)
开发语言·python·数码相机·算法
看我干嘛!1 小时前
python第五次作业
算法
历程里程碑1 小时前
Linux 库
java·linux·运维·服务器·数据结构·c++·算法
Sheep Shaun1 小时前
如何让一个进程诞生、工作、终止并等待回收?——探索Linux进程控制与Shell的诞生
linux·服务器·数据结构·c++·算法·shell·进程控制
Pluchon1 小时前
硅基计划4.0 简单模拟实现AVL树&红黑树
java·数据结构·算法