• 662. 二叉树最大宽度


    题目描述

    给你一棵二叉树的根节点 root ,返回树的 最大宽度 。

    树的 最大宽度 是所有层中最大的 宽度 。

    每一层的 宽度 被定义为该层最左和最右的非空节点(即,两个端点)之间的长度。将这个二叉树视作与满二叉树结构相同,两端点间会出现一些延伸到这一层的 null 节点,这些 null 节点也计入长度。

    题目数据保证答案将会在 32 位 带符号整数范围内


    做题思路

    • 通过这个题目我学习到了一种集合 Pair

      Map可以存储一堆的 (K,V)对,如果我们只想存储一个KV对

      那就会浪费空间,为了解决只存储一个K,V对的问题

      引入了 Pair,方法和HashMap大同小异,只不过只能存储

      一个KV对

    • 再说说本题:让我们求宽度

      前置知识:

      根节点坐标 :i

      左孩子结点坐标:2*i

      右孩子结点坐标:2*i+1

      我们可以通过广度优先遍历的思想,遍历每一层,一层一层的比较找出最大的宽度

      其实本题的实现就是再层序遍历的基础上做一些判断比较即可

      总体来说还是很有挑战性的

    代码实现

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public int widthOfBinaryTree(TreeNode root) {
            if(root==null){
                return 0;
            }
            List<Pair<TreeNode,Integer>> arr=new ArrayList<>();
            arr.add(new Pair<TreeNode,Integer>(root,1));
            int max=1;
            while(!arr.isEmpty()){
                List<Pair<TreeNode,Integer>> tem=new ArrayList<>();
                for(Pair<TreeNode,Integer> pair:arr){
                    TreeNode node=pair.getKey();
                    int v=pair.getValue();
                    if(node.left!=null){
                        tem.add(new Pair<TreeNode,Integer>(node.left,2*v));
                    }
                    if(node.right!=null){
                        tem.add(new Pair<TreeNode,Integer>(node.right,2*v+1));
                    }
                }
                if(!tem.isEmpty()){
                    max=Math.max(max,tem.get(tem.size()-1).getValue()-tem.get(0).getValue()+1);
                }
                arr=tem;
            }
            return max;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    题目链接

    662. 二叉树最大宽度

  • 相关阅读:
    基于ssm的教师贴心宝管理系统的设计与实现-计算机毕业设计源码
    Jenkins集成Kubernetes集群
    Linux运维基础知识大全
    AWS EC2入门指南中创建和配置云虚拟机实例的基本步骤
    链上信使协议AMOP
    合规性管理如何帮助产品团队按时交付?
    DevOps --- Pipeline和Yaml文件
    以太坊合并在即 生态用户需要注意什么?
    10 分钟彻底理解 Redis 的持久化和主从复制
    Dubbo之注册与发现
  • 原文地址:https://blog.csdn.net/C_x_330/article/details/127784003