亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么以下代碼會生成運行時錯誤?

為什么以下代碼會生成運行時錯誤?

RISEBY 2021-11-12 15:37:03
給定一個沒有重復的整數數組。在此數組上構建的最大樹定義如下:根是數組中的最大數。左子樹是由左部分子數組除以最大數構造的最大樹。右子樹是由右部分子數組除以最大數構造的最大樹。通過給定數組構造最大樹并輸出該樹的根節點。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]));
查看完整描述

1 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

問題是線路


let maxindex = 0;

您只關心從low到范圍的最大元素high。如果nums[0]高于該范圍內的任何元素,您將找不到它,也不會正確劃分該子序列。這導致無限遞歸。


將其更改為:


let maxindex = low;

以便它只與范圍內的元素進行比較。您可以從 開始for循環low+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 = low;

  for (let i = low+1; 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]));


查看完整回答
反對 回復 2021-11-12
  • 1 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號