首页 > 其他分享 >662. 二叉树最大宽度

662. 二叉树最大宽度

时间:2022-08-27 22:55:57浏览次数:91  
标签:node 662 宽度 二叉树 null root 节点

662. 二叉树最大宽度

给你一棵二叉树的根节点 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
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
type pair struct {
    node  *TreeNode
    index int
}

func widthOfBinaryTree(root *TreeNode) int {
    ans := 1
    q := []pair{{root, 1}}
    for q != nil {
        // 该层最后一个节点减去最左边节点的索引值
        ans = max(ans, q[len(q)-1].index-q[0].index+1)
        tmp := q
        q = nil
        for _, p := range tmp {
            // 左子树和右子树的索引值分别为其父亲节点索引的两倍和两倍加1
            if p.node.Left != nil {
                q = append(q, pair{p.node.Left, p.index * 2})
            }
            if p.node.Right != nil {
                q = append(q, pair{p.node.Right, p.index*2 + 1})
            }
        }
    }
    return ans
}

func max(a, b int) int {
    if b > a {
        return b
    }
    return a
}

 

标签:node,662,宽度,二叉树,null,root,节点
From: https://www.cnblogs.com/fulaien/p/16631724.html

相关文章

  • 二叉树
    1树的结构 1.1树的概念:树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。有一个特殊的节点叫根节点,根节点没有前驱。其余节点被分成......
  • 222.count-complete-tree-nodes 完全二叉树的节点个数
    遍历法遍历所有节点的方法,时间复杂度为\(O(n)\)classSolution{public:intcountNodes(TreeNode*root){if(root==nullptr)return0......
  • 101. 对称二叉树
    101.对称二叉树给你一个二叉树的根节点root,检查它是否轴对称。 示例1:输入:root=[1,2,2,3,4,4,3]输出:true示例2:输入:root=[1,2,2,null,3,null,3]输出:fa......
  • leetcode144:二叉树的前序遍历
    packagecom.mxnet;importjava.util.ArrayList;importjava.util.List;publicclassSolution144{publicstaticvoidmain(String[]args){}/**......
  • leetcode226-翻转二叉树
    翻转二叉树递归classSolution{publicTreeNodeinvertTree(TreeNoderoot){if(root==null)returnroot;TreeNodel=invertTree(roo......
  • leetcode222-完全二叉树的节点个数
    完全二叉树的节点个数递归classSolution{publicintcountNodes(TreeNoderoot){if(root==null)return0;returncountNodes(root.le......
  • 平衡二叉树(AVL)的实现
    平衡二叉树概念平衡二叉排序树(BalancedBinaryTree),因由前苏联数学家Adelson-Velskii和Landis于1962年首先提出的,所以又称为AVL树。平衡二叉树是一种特殊的二叉排序......
  • 二叉树的结构
    https://www.acwing.com/problem/content/description/4274/#include<bits/stdc++.h>#include<string.h>usingnamespacestd;constintN=1010;intpost[N],in[N......
  • 判断是不是平衡二叉树
    staticintflag=0;publicbooleanisBalanced(TreeNoderoot){flag=0;travel12(root);if(flag==1){returnfalse;......
  • leetcode 热题100刷题-二叉树的中序遍历
    题题号:94题目:二叉树的中序遍历难度:简单链接:https://leetcode.cn/problems/binary-tree-inorder-traversal/2022/08/23答案算法思路  本题在课程中是学过的。  ......