LeetCode 654 最大二叉树

163 阅读1分钟

题目描述:给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的 最大二叉树 定义如下:

  • 二叉树的根是数组 nums 中的最大元素。
  • 左子树是通过数组中 最大值左边部分 递归构造出的最大二叉树。
  • 右子树是通过数组中 最大值右边部分 递归构造出的最大二叉树。
  • 返回有给定数组 nums 构建的 最大二叉树 。

image.png

var constructMaximumBinaryTree = function(nums) {
   let root = buildTree(nums, 0, nums.length-1)
   return root

   function buildTree(arr, left, right){
       // 递归出口
       if(left > right){
           return null
       }
        // 找出最大值和下标
        let maxValue = -1
        let index = -1
        for(let i=left;i<=right;i++){
            if(maxValue < arr[i]){
                maxValue = arr[i]
                index = i
            }
        }
        let root = new TreeNode(maxValue)
        // 递归
        root.left = buildTree(arr, left, index-1)
        root.right = buildTree(arr, index+1, right)
        return root
    }
};