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
Balanced Organization HierarchyExperience Levels: [1, 3, 5, 7, 9] yearsCEO5 yrsMgr3 yrsMgr7 yrs1 yr9 yrsโœ“ Balanced Teamsโœ“ Efficient Communicationโœ“ Optimal Management LevelsKey: Choose middle element as root!
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ยฒ)

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for n tree nodes, plus O(n) recursion stack in worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -104 โ‰ค nums[i] โ‰ค 104
  • nums is sorted in a strictly increasing order
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28 Apple 22
89.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen