为什么以下代码会生成运行时错误?

给定一个没有重复的整数数组。在此数组上构建的最大树定义如下:


根是数组中的最大数。左子树是由左部分子数组除以最大数构造的最大树。右子树是由右部分子数组除以最大数构造的最大树。通过给定数组构造最大树并输出该树的根节点。


Input: [3,2,1,6,0,5]

Output: return the tree root node representing the following tree:


      6

    /   \

   3     5

    \    / 

     2  0   

       \

        1

/**

 * Definition for a binary tree node.

 */

function TreeNode(val) {

  this.val = val;

  this.left = this.right = null;

}


/**

 * @param {number[]} nums

 * @return {TreeNode}

 */

var constructMaximumBinaryTree = function(nums) {

  if (nums == null)

    return null;

  return helper(nums, 0, nums.length - 1);

};


function helper(nums, low, high) {

  if (low > high) {

    return null;

  }

  let maxIndex = 0;

  for (let i = low; i <= high; i++) {

    if (nums[maxIndex] < nums[i]) {

      maxIndex = i;

    }

  }

  let node = new TreeNode(nums[maxIndex]);

  node.left = helper(nums, 0, maxIndex - 1);

  node.right = helper(nums, maxIndex + 1, high);

  return node;

};


console.log(constructMaximumBinaryTree([3,2,1,6,0,5]));


RISEBY
浏览 149回答 1
1回答

手掌心

问题是线路let maxindex = 0;您只关心从low到范围的最大元素high。如果nums[0]高于该范围内的任何元素,您将找不到它,也不会正确划分该子序列。这导致无限递归。将其更改为:let maxindex = low;以便它只与范围内的元素进行比较。您可以从 开始for循环low+1。/**&nbsp;* Definition for a binary tree node.&nbsp;*/function TreeNode(val) {&nbsp; this.val = val;&nbsp; this.left = this.right = null;}/**&nbsp;* @param {number[]} nums&nbsp;* @return {TreeNode}&nbsp;*/var constructMaximumBinaryTree = function(nums) {&nbsp; if (nums == null)&nbsp; &nbsp; return null;&nbsp; return helper(nums, 0, nums.length - 1);};function helper(nums, low, high) {&nbsp; if (low > high) {&nbsp; &nbsp; return null;&nbsp; }&nbsp; let maxIndex = low;&nbsp; for (let i = low+1; i <= high; i++) {&nbsp; &nbsp; if (nums[maxIndex] < nums[i]) {&nbsp; &nbsp; &nbsp; maxIndex = i;&nbsp; &nbsp; }&nbsp; }&nbsp; let node = new TreeNode(nums[maxIndex]);&nbsp; node.left = helper(nums, 0, maxIndex - 1);&nbsp; node.right = helper(nums, maxIndex + 1, high);&nbsp; return node;};console.log(constructMaximumBinaryTree([3,2,1,6,0,5]));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript