Problem 108 · LeetCode 108(opens in a new tab)
Convert Sorted Array to Binary Search Tree
EasyDivide and conquer
You get an array nums of distinct integers sorted from smallest to largest. Build a binary search tree that holds every value, and make it height-balanced: at every node, the heights of the left and right subtrees differ by at most 1.
Return the root. Many trees can qualify; any balanced search tree with exactly these values is accepted.
Example 1
Input: nums = [-4, 1, 3, 7, 10, 15, 20] Output: [7, 1, 15, -4, 3, 10, 20] Why: 7 sits in the middle, three values on each side
2 more examples and the constraints
Example 2
Input: nums = [2, 5] Output: [2, null, 5] Why: [5, 2] is just as balanced, and also accepted
Example 3
Input: nums = [-3, 0, 6, 8] Output: [0, -3, 6, null, null, null, 8] Why: an even count leaves one side a node longer
Constraints
- 1 ≤ length of nums ≤ 10,000
- −10,000 ≤ nums[i] ≤ 10,000
- nums is sorted in strictly increasing order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recurse on copied halvesO(n log n)
- Recurse on index boundsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 values | Verdict |
|---|---|---|---|
| Recurse on copied halves | O(n log n) | Right shape; wasteful copies | |
| Recurse on index bounds | O(n) | Best; each value touched once |
n = number of values in nums.
Edge cases to test
- One value. The tree is a single node with no children.
- Two values. One becomes the root and the other its child, on either side.
- Even count. There is no single middle; either middle works, but pick one rule and keep it.
- A perfect size. With 7 or 15 values, every level fills completely.
- Large input. 10,000 values give a depth of only 14, so recursion is safe.
Common mistakes
- Inserting the values one by one into an empty BST, which builds a chain of height n.
- Using
build(lo, mid)instead ofbuild(lo, mid − 1), which loops forever on a range of one. - Stopping at
lo == hiinstead oflo > hi, so a leaf's value never gets a node.
How to talk through it
- 1Clarify. Are the values distinct? Is any balanced tree accepted, or one particular shape?
- 2Name the key fact. In a BST, the in-order walk is sorted. So the middle of the array must be the root.
- 3Give the copying version. Split the array, recurse on copies: right shape, O(n log n) time.
- 4Drop the copies. Pass
loandhiinstead. Each call does O(1) work, so the whole build is O(n). - 5Test out loud. Run one value, two values and an even count, and check the heights.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?