1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| var constructMaximumBinaryTree = function (nums) { var recusive = function (nums, left, right) { if (left > right) { return null; } const [rootValue, rootIndex] = findMaxValueAndIndex(nums, left, right); const root = new TreeNode(rootValue); if (left < rootIndex) { root.left = recusive(nums, left, rootIndex - 1); } if (rootIndex < right) { root.right = recusive(nums, rootIndex + 1, right); } return root; }; return recusive(nums, 0, nums.length - 1); };
var findMaxValueAndIndex = function (nums, left, right) { let max = nums[left]; let maxIndex = left; for (let i = left + 1; i <= right; i++) { const currentValue = nums[i]; if (currentValue > max) { max = currentValue; maxIndex = i; } } return [max, maxIndex]; };
|