8000 Added sortedArrayToBST.js · jonasraoni/leetcode@9c7f218 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9c7f218

Browse files
committed
Added sortedArrayToBST.js
1 parent 022cae3 commit 9c7f218

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

easy/sortedArrayToBST.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//+ Jonas Raoni Soares Silva
2+
//@ http://raoni.org
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {number[]} nums
14+
* @return {TreeNode}
15+
*/
16+
var sortedArrayToBST = function(nums) {
17+
return new function nodeFromMiddle(start = 0, end = nums.length - 1, middle = (start + end) >> 1) {
18+
return end < start || start >= nums.length ? null : new TreeNode(nums[middle], nodeFromMiddle(start, middle - 1), nodeFromMiddle(middle + 1, end));
19+
};
20+
};

easy/sortedArrayToBST.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# [108. Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree)
2+
3+
Given an integer array nums where the elements are sorted in ascending order, convert it to a
4+
height-balanced
5+
binary search tree.
6+
7+
8+
9+
Example 1:
10+
11+
12+
Input: nums = [-10,-3,0,5,9]
13+
Output: [0,-3,9,-10,null,5]
14+
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
15+
16+
Example 2:
17+
18+
19+
Input: nums = [1,3]
20+
Output: [3,1]
21+
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
22+
23+
24+
Constraints:
25+
26+
1 <= nums.length <= 104
27+
-104 <= nums[i] <= 104
28+
nums is sorted in a strictly increasing order.

0 commit comments

Comments
 (0)
0