Skip to content

Commit 9ed02a3

Browse files
committed
Create 654. 最大二叉树.js
1 parent 33f72cf commit 9ed02a3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

654. 最大二叉树.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
if (nums.length === 0) {
15+
return null;
16+
}
17+
let max = 0;
18+
for (let i = 1; i < nums.length; i++) {
19+
if (nums[i] > nums[max]) {
20+
max = i;
21+
}
22+
}
23+
return new TreeNode(
24+
nums[max],
25+
constructMaximumBinaryTree(nums.slice(0, max)),
26+
constructMaximumBinaryTree(nums.slice(max + 1)),
27+
);
28+
};

0 commit comments

Comments
 (0)