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]));
添加回答
舉報