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:
[3,1]
💡 Note:
For even length, we pick right middle (index 1). Element 3 becomes root with left child 1.
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
Understanding the Visualization
1
Sorted Array
Input array in ascending order
2
Pick Middle
Choose middle element as root for balance
3
Balanced BST
Recursively built balanced binary search tree
Key Takeaway
🎯 Key Insight: Always choose the middle element as root to maintain perfect balance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code