likes
comments
collection
share

leetcode刷题记录-654. 最大二叉树

作者站长头像
站长
· 阅读数 21

前言

今天的题目为中等,但是实际做起来算是比较简单,因为题目把要求都说好了,只要根据题目说的进行简单递归即可

每日一题

今天的题目是 654. 最大二叉树,难度为中等

  • 给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:

  • 创建一个根节点,其值为 nums 中的最大值。

  • 递归地在最大值 左边 的 子数组前缀上 构建左子树。

  • 递归地在最大值 右边 的 子数组后缀上 构建右子树。

  • 返回 nums 构建的 最大二叉树 。

 

示例 1:

leetcode刷题记录-654. 最大二叉树

输入:nums = [3,2,1,6,0,5]
输出:[6,3,5,null,2,0,null,null,1]
解释:递归调用如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。
    - [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。
        - 空数组,无子节点。
        - [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。
            - 空数组,无子节点。
            - 只有一个元素,所以子节点是一个值为 1 的节点。
    - [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。
        - 只有一个元素,所以子节点是一个值为 0 的节点。
        - 空数组,无子节点。

示例 2:

leetcode刷题记录-654. 最大二叉树

输入:nums = [3,2,1]
输出:[3,null,2,null,1]

 

提示:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • nums 中的所有整数 互不相同

题解

递归

简单递归,根据题目的要求,不断递归取寻找数组中的最大的元素作为当前的结点,在找到最大的结点以后,当前结点的左边就是左孩子,右边就是右孩子,对于左右两边的处理也是完全相同的,相当于是找到最大结点作为当前结点以后,将数组的左边以及右边进行分割,分别进行递归,继续去左边以及右边寻找最大值构建树。

所以我们首先找到数组的最大值,并且创建结点作为当前结点的值,根据最大值进行数组分割,分为左边和右边,然后左边和右边数组又可以递归进入函数去创建左孩子和右孩子。

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
    if(nums.length == 0) return null
    let max: number = 0
    let index: number = 0
    nums.forEach((e,i)=>{
        if(e > max) {
            max = e
            index = i
        }
    })
    const left = nums.slice(0, index)
    const right = nums.slice(index+1)
    const root = new TreeNode(max)
    root.left = constructMaximumBinaryTree(left)
    root.right = constructMaximumBinaryTree(right)
    return root 
};

leetcode刷题记录-654. 最大二叉树