Sorted array to a balanced BST
Easytreebinary search treedivide and conquer
nums is sorted ascending with no duplicates. Build a balanced binary search tree: the root is the middle element and each side is built the same way. With an even count take the left middle: mid = floor((lo + hi) / 2).
Examples write a tree level by level, with null for a missing child: [3,9,20,null,null,15,7].
Example 1
Input: nums = [-10,-3,0,5,9] Output: [0,-10,5,null,-3,null,9]
Example 2
Input: nums = [1,3] Output: [1,null,3]
Constraints
- 1 ≤ nums.length ≤ 10⁴
- nums is strictly increasing
Submit checks your solution against 8 tests, including hidden ones.
// Provided by the judge: keep these definitions
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
}
/**
* @param {int[]} nums
* @return {TreeNode|null}
*/
function sortedArrayToBST(nums) {
}