Skip to content

Commit 5391273

Browse files
committed
added Function
1 parent 80a4ffe commit 5391273

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Maximum Binary Tree/code.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/*
10+
* @param {number[]} nums
11+
* @return {TreeNode}
12+
*/
13+
var constructMaximumBinaryTree = function(nums) {
14+
15+
return next(0, nums.length - 1);
16+
17+
function next(l, r) {
18+
if (l > r) return null;
19+
let maxIndex = -1, max = -Infinity;
20+
for (let i = l; i <= r; i++) {
21+
if (nums[i] > max) {
22+
maxIndex = i;
23+
max = nums[i];
24+
}
25+
}
26+
return {
27+
val: max,
28+
left: next(l, maxIndex - 1),
29+
right: next(maxIndex + 1, r)
30+
}
31+
}
32+
};
33+

0 commit comments

Comments
 (0)