Convert Sorted Array to Binary Search Tree - Problem
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than 1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [-10,-3,0,5,9]
›
Output:
[0,-3,9,-10,null,5]
💡 Note:
Middle element 0 becomes root. Left subtree from [-10,-3] has root -3 with left child -10. Right subtree from [5,9] has root 9 with left child 5.
Example 2 — Even Length Array
$
Input:
nums = [1,3]
›
Output:
[1,null,3]
💡 Note:
For even length, we pick left middle (index 0). Element 1 becomes root with right child 3.
Example 3 — Single Element
$
Input:
nums = [0]
›
Output:
[0]
💡 Note:
Single element becomes the root with no children.
Constraints
- 1 ≤ nums.length ≤ 104
- -104 ≤ nums[i] ≤ 104
- nums is sorted in strictly increasing order
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code