Convert Sorted Array to Binary Search Tree — Solution
Convert Sorted Array to Binary Search Tree solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript.
Convert Sorted Array to Binary Search Tree is an easy coding problem on arrays, trees and divide and conquer, asked in Amazon, Google, Microsoft and Meta interviews.
- Difficulty: Easy
- Topics: Arrays, Trees, Divide and Conquer
- Asked at: Amazon, Google, Microsoft, Meta
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given an integer array nums sorted in strictly increasing order. Build a height-balanced binary search tree holding exactly these values — one in which the depths of the two subtrees of every node differ by at most one — and return its root.
Many balanced trees are possible, so build this one: the root of every range nums[lo..hi] is its left-middle element nums[(lo + hi) / 2] (integer division), the elements before it form the left subtree and the elements after it the right subtree, built the same way.
Example 1
Input: nums = [-10,-3,0,5,9]
Output: [0,-10,5,null,-3,null,9]
Explanation: 0 is the middle element. The left half [-10,-3] takes its left-middle -10 as root with -3 to its right; the right half [5,9] likewise takes 5 with 9 to its right.
Example 2
Input: nums = [1,3]
Output: [1,null,3]
Explanation: With two elements the left-middle one, 1, is the root.
Example 3
Input: nums = [7]
Output: [7]
Explanation: A single element is a single node.
Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i] <= 10^4nums is sorted in strictly increasing order
Hints for Convert Sorted Array to Binary Search Tree
Hint 1
The root of a balanced search tree over a sorted range should split the range into two halves of nearly equal size.
Hint 2
Once the root is chosen, the left and right halves are the same problem on smaller ranges.
Hint 3
Recurse on index ranges
[lo, hi]withmid = (lo + hi) / 2; an empty range (lo > hi) gives null.
How to solve Convert Sorted Array to Binary Search Tree
In-order traversal of a search tree is the sorted array, so any node can root a range as long as smaller elements go left and larger go right. Choosing the middle element each time keeps the two sides within one element of each other, which keeps the tree balanced.
Approach
- Define
build(lo, hi): iflo > hi, return null. - Let
mid = (lo + hi) / 2and create a node withnums[mid]. - Set its left child to
build(lo, mid - 1)and its right child tobuild(mid + 1, hi). - Return
build(0, n - 1).
Why it works
Every element left of mid is smaller and every element right of it is larger, so the search-tree property holds at each node. The two halves differ in size by at most one, so by induction their heights differ by at most one as well.
Complexity
- Time —
O(n) - Space —
O(log n) for the recursion (plus the n nodes of the answer)
Pitfalls
- Use the left-middle element
(lo + hi) / 2, as the statement fixes — the right-middle also balances but builds a different tree. - Pass indices, not copies of sub-arrays, or the copying costs O(n log n).
Reference solution
Python
from typing import List, Optional
def sortedArrayToBST(nums: List[int]) -> Optional[TreeNode]:
def build(lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
mid = (lo + hi) // 2
return TreeNode(nums[mid], build(lo, mid - 1), build(mid + 1, hi))
return build(0, len(nums) - 1)Java
public static TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length - 1);
}
static TreeNode build(int[] nums, int lo, int hi) {
if (lo > hi) return null;
int mid = (lo + hi) / 2;
return new TreeNode(nums[mid], build(nums, lo, mid - 1), build(nums, mid + 1, hi));
}C++
TreeNode* build(vector<int>& nums, int lo, int hi);
TreeNode* sortedArrayToBST(vector<int>& nums) {
return build(nums, 0, (int) nums.size() - 1);
}
TreeNode* build(vector<int>& nums, int lo, int hi) {
if (lo > hi) return nullptr;
int mid = (lo + hi) / 2;
return new TreeNode(nums[mid], build(nums, lo, mid - 1), build(nums, mid + 1, hi));
}JavaScript
var sortedArrayToBST = function(nums) {
return build(nums, 0, nums.length - 1);
};
var build = function(nums, lo, hi) {
if (lo > hi) return null;
var mid = (lo + hi) >> 1;
return new TreeNode(nums[mid], build(nums, lo, mid - 1), build(nums, mid + 1, hi));
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Binary Trees and Tree Traversals