-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-binary-tree.js
64 lines (54 loc) · 1.7 KB
/
maximum-binary-tree.js
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var constructMaximumBinaryTree = function (nums) {
// 分而治之
// 需要分割数组, 会产生了额外的内存开销
if (nums.length === 0) return null;
let maxIndex = findMaxValueIndex(nums);
let rootValue = nums[maxIndex];
let left = nums.slice(0, maxIndex);
let right = nums.slice(maxIndex + 1);
const node = new TreeNode(rootValue);
node.left = constructMaximumBinaryTree(left);
node.right = constructMaximumBinaryTree(right);
return node;
// 优化: 不分割数组,而是通过下标索引在原数组上操作
// return constructMaximumBinaryTree2(nums, 0, nums.length);
};
// 优化: 不分割数组,而是通过下标索引在原数组上操作
function constructMaximumBinaryTree2(nums) {
const helper = (nums, start, end) => {
// [3,2,1,6,0,5]
if (start === end) return null;
const index = findMaxValueIndex(nums, start, end);
const val = nums[index];
const root = new TreeNode(val);
if (end - start === 1) return root;
// 左闭右开
// [start, index)
root.left = helper(nums, start, index);
// [index + 1, end)
root.right = helper(nums, index + 1, end);
return root;
}
return helper(nums, 0, nums.length);
}
function findMaxValueIndex(array, start = 0, end = array.length) {
let maxIndex = start;
for (let i = start + 1; i < end; i++) {
if (array[maxIndex] < array[i]) {
maxIndex = i;
}
}
return maxIndex;
}