Skip to content

Commit 38fad5b

Browse files
committed
solved: 108
1 parent 3a1f373 commit 38fad5b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
// @leet start
13+
/**
14+
* Definition for a binary tree node.
15+
* class TreeNode {
16+
* val: number
17+
* left: TreeNode | null
18+
* right: TreeNode | null
19+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.left = (left===undefined ? null : left)
22+
* this.right = (right===undefined ? null : right)
23+
* }
24+
* }
25+
*/
26+
27+
function sortedArrayToBST(nums: number[]): TreeNode | null {
28+
if (nums.length === 0) return null;
29+
30+
/* array is sorted, so define the root, which is the middle element */
31+
const rootIndex = Math.floor(nums.length / 2);
32+
const root = new TreeNode(nums[rootIndex]);
33+
34+
/* recursively create left & right */
35+
root.left = sortedArrayToBST(nums.slice(0, rootIndex));
36+
root.right = sortedArrayToBST(nums.slice(rootIndex + 1));
37+
38+
return root;
39+
}
40+
// @leet end
41+

0 commit comments

Comments
 (0)