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 one.
Goal: Transform a sorted array into a balanced BST where all left descendants are smaller and all right descendants are larger than the parent node.
Example: Array [1, 3, 5, 7, 9] should become a BST with root 5, left subtree containing [1, 3], and right subtree containing [7, 9].
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [-10,-3,0,5,9]
โบ
Output:
[0,-3,9,-10,null,5]
๐ก Note:
The middle element 0 becomes root. Left subtree is built from [-10,-3] with -3 as root and -10 as left child. Right subtree is built from [5,9] with 9 as root and 5 as left child.
example_2.py โ Single Element
$
Input:
nums = [1]
โบ
Output:
[1]
๐ก Note:
Array with single element creates a tree with just the root node containing that element.
example_3.py โ Even Length Array
$
Input:
nums = [1,3]
โบ
Output:
[3,1] or [1,null,3]
๐ก Note:
For even length arrays, we can choose either middle element (index 0 or 1). Both create valid height-balanced BSTs.
Visualization
Tap to expand
Understanding the Visualization
1
Find the Middle Manager
Choose the employee with median experience as the department head
2
Organize Left Team
Recursively organize less experienced employees under left management
3
Organize Right Team
Recursively organize more experienced employees under right management
4
Balanced Structure
Result is an efficient hierarchy with minimal communication overhead
Key Takeaway
๐ฏ Key Insight: The middle element of a sorted array is the perfect choice for a balanced BST root, as it naturally divides the remaining elements into two equal halves, recursively creating optimal balance.
Time & Space Complexity
Time Complexity
O(nยฒ)
Each insertion takes O(height) time, and height grows to n, so total is O(nยฒ)
โ Quadratic Growth
Space Complexity
O(n)
Space for n tree nodes, plus O(n) recursion stack in worst case
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 104
- -104 โค nums[i] โค 104
- nums is sorted in a strictly increasing order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code