【剑斩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;
    }
};
相关推荐
大白话_NOI20 小时前
【洛谷 P1303】A*B Problem + 详细分析
c++
小欣加油20 小时前
leetcode2161 根据给定数字划分数组
数据结构·c++·算法·leetcode·职场和发展
吃着火锅x唱着歌21 小时前
深度探索C++对象模型 学习笔记 第五章 构造、解构、拷贝语意学(2)
c++·笔记·学习
玖釉-21 小时前
Vulkan 离屏渲染详解:从 Framebuffer 到后处理、阴影贴图与 Render Texture
c++·windows·计算机视觉·图形渲染
Momo__zz21 小时前
零代码平台设计
算法·深度优先
cpp_250121 小时前
P2947 [USACO09MAR] Look Up S
数据结构·c++·算法·题解·单调栈·洛谷
楼田莉子21 小时前
C++20新特性:协程
开发语言·c++·后端·学习·c++20
炘爚21 小时前
phase1:基础框架——编译 + MySQL + 登录/注册
linux·c++
水木流年追梦21 小时前
大模型入门-大模型优化方法13- MTP 多 token 输出、DCA 双块注意力
人工智能·分布式·算法·正则表达式·prompt
特种加菲猫21 小时前
C++11核心特性深度解析:从列表初始化到lambda与包装器
开发语言·c++