【剑斩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;
    }
};
相关推荐
超级码力6668 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
穿条秋裤到处跑8 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
Merlos_wind9 小时前
HashMap详解
算法·哈希算法·散列表
汉克老师9 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Yzzz-F12 小时前
Problem - 2205D - Codeforces
算法
智者知已应修善业12 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
Halo_tjn12 小时前
Java Set集合相关知识点
java·开发语言·算法
生成论实验室13 小时前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
AI科技星13 小时前
全域数学·72分册:场计算机卷【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算
云泽80814 小时前
C++11 核心特性全解:列表初始化、右值引用与移动语义实战
开发语言·c++