Leetcode662_二叉树最大宽度

1.leetcode原题链接:. - 力扣(LeetCode)

2.题目描述

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

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

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

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

示例 1:

输入:root = [1,3,2,5,3,null,9]
输出:4
解释:最大宽度出现在树的第 3 层,宽度为 4 (5,3,null,9) 。

示例 2:

输入:root = [1,3,2,5,null,null,9,6,null,7]
输出:7
解释:最大宽度出现在树的第 4 层,宽度为 7 (6,null,null,null,null,null,7) 。

示例 3:

输入:root = [1,3,2,5]
输出:2
解释:最大宽度出现在树的第 2 层,宽度为 2 (3,2) 。

提示:

  • 树中节点的数目范围是 [1, 3000]
  • -100 <= Node.val <= 100

3.实现方法

思路:存储二叉树的下标,每个节点下标为 N,左子树结点为 2 * N,右子树下标为 2 * N+1。
然后进行层次遍历,每次比较最大宽度值。

层序遍历:Leetcode102_二叉树的层序遍历-CSDN博客

/**
 * 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;
        }
        int result = 0;
        Deque<TreeNode> queue =new LinkedList<>();
        root.val=1;
        queue.offer(root);
    
        while(!queue.isEmpty()){
            int size = queue.size();
            result = Math.max(result,queue.getLast().val - queue.getFirst().val+1);
            for(int i=0;i<size;i++){
                TreeNode node =queue.poll();
                if(node.left != null){
                    node.left.val = node.val*2;
                    queue.offer(node.left);
                }
                if(node.right != null){
                    node.right.val = node.val *2 +1;
                    queue.offer(node.right);
                }
            }
        }
        return result;
	}
}

相关推荐

  1. 106宽度

    2024-04-27 11:42:02       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-27 11:42:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-27 11:42:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-27 11:42:02       82 阅读
  4. Python语言-面向对象

    2024-04-27 11:42:02       91 阅读

热门阅读

  1. c++day4

    c++day4

    2024-04-27 11:42:02      26 阅读
  2. 【Redis 开发】分布式锁中的常见问题和Lua脚本

    2024-04-27 11:42:02       28 阅读
  3. 使用 NVM 管理 Node.js 版本

    2024-04-27 11:42:02       32 阅读
  4. leetcode 27 原地删除有序数组

    2024-04-27 11:42:02       32 阅读
  5. 嵌入式前后台(Bare-Metal RTOS-Like)架构详解

    2024-04-27 11:42:02       29 阅读
  6. Kubernetes的原理及应用详解(五)

    2024-04-27 11:42:02       31 阅读
  7. ChatGPT-税收支持新质生产力

    2024-04-27 11:42:02       26 阅读
  8. Git Tag 打标签

    2024-04-27 11:42:02       32 阅读
  9. C#算法之归并排序

    2024-04-27 11:42:02       32 阅读
  10. 消费者处理消息失败如何解决

    2024-04-27 11:42:02       39 阅读