最大二叉树

96 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第25天,点击查看活动详情

题目:

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

创建一个根节点,其值为 nums 中的最大值。 递归地在最大值 左边 的 子数组前缀上 构建左子树。 递归地在最大值 右边 的 子数组后缀上 构建右子树。 返回 nums 构建的 最大二叉树 。

示例1:

image.png

输入: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:

image.png

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

思路分析:

采用递归的方法。先获取到根节点,根节点的要求是数组中的最大值,所以获取最大值后再取得索引。0到(索引-1)处为左子树,(索引+1)到(nums.length)为右子树。并将左子树与右子树赋值给已经获得的最大值(上一步的根节点)。递归这个操作。

代码实现:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var constructMaximumBinaryTree = function(nums) {
     if(nums.length===0){
         return null;
     }
     let max = Math.max(...nums);
     let index = nums.indexOf(max)
     let node = new TreeNode(max);
     let left = constructMaximumBinaryTree(nums.slice(0,index));
     let right = constructMaximumBinaryTree(nums.slice(index+1,nums.length));
     node.left = left;
     node.right = right;
     return node;
};

提交记录:

image.png