Convert Sorted Array to Binary Search Tree
EasyP2Coding
Given an integer array nums sorted in ascending order, build a height-balanced binary search tree from it and return its root.
Many balanced trees are valid, so this problem asks for one canonical shape: for the range lo..hi (inclusive), the root is the element at index floor((lo + hi) / 2), which is the left of the two middle elements when the range has even length. Build the left subtree from the part before it and the right subtree from the part after it.
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]
- Why
- The range has two elements, so the left middle (1) becomes the root and 3 is its right child.
Constraints
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- nums is strictly increasing.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.