-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaximumBinaryTree.JJ.js
37 lines (29 loc) · 1.14 KB
/
MaximumBinaryTree.JJ.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
/*
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
*/
function TreeNode(val, left, right) {
this.val = val;
this.left = left || null;
this.right = right || null;
}
function constructMaximumBinaryTree(array) {
if(!array.length || !array) return null
const maxIndex = findMaxIndex(array)
const leftHalfSorted = array.slice(0, maxIndex)
const rightHalfSorted = array.slice(maxIndex + 1, array.length)
const root = new TreeNode(array[maxIndex])
root.left = constructMaximumBinaryTree(leftHalfSorted)
root.right = constructMaximumBinaryTree(rightHalfSorted)
return root
}
function findMaxIndex(array) {
let index = 0
array.forEach((ele, i) => {
if (ele > array[index]) index = i
})
return index
}