Problem overview
The method sortedArrayToBST receives an int[] named nums, sorted in strictly increasing order, and returns the root of a height-balanced binary search tree holding exactly those values. Height-balanced means that for every node, the heights of its left and right subtrees differ by at most one. A binary search tree keeps smaller values in the left subtree and larger values in the right one.
For nums = [-10, -3, 0, 5, 9], one valid answer has 0 at the root, -10 and 5 as its children, then -3 under -10 and 9 under 5. Several trees can be correct. For [1, 3], both [3, 1] and [1, null, 3] are balanced, and either shape is acceptable.
Approach: the middle element is the root
Because the array is already sorted, an in-order walk of the finished tree must read the values in exactly this order. That settles which values go where once a root is chosen: everything before the root's position goes into its left subtree, and everything after goes into its right subtree.
The choice of root decides the shape. Always taking the first element would put every other value in the right subtree, producing a chain as deep as the array, which is a valid BST but not a balanced one. Taking the middle element splits the values into two halves whose sizes differ by at most one. Applying the same idea to each half gives subtrees of nearly equal height at every level, so the whole tree is balanced and its height is about log n.
The recursion is therefore: pick the middle of the current range, make it a node, build the left half as the left child and the right half as the right child. An empty range yields no node.
On [-10, -3, 0, 5, 9] the middle index is 2, so 0 is the root. The left range [-10, -3] has middle index 0, so -10 becomes its root and -3 its right child. The right range [5, 9] works the same way, with 5 as the root and 9 as its right child.
Step by step
- Call a helper from the main method.
sortedArrayToBSTpassesnums, the first index0and the last indexnums.length - 1tobuild, and returns what it gets back. - Pass index bounds instead of slices. The helper takes
leftandrightto name the part of the array it owns. Every call shares the same array, and no copies are made. - Handle the empty range first. When
left > right, the range holds no elements, so the helper returnsnull. This is what ends the recursion, and it happens often: the halves of a one-element range are both empty. - Find the middle index.
(left + right) / 2uses integer division, which drops the fraction. For a range with an even number of elements this picks the lower of the two middle positions. - Create the node with the value
nums[mid]. - Build the left subtree from
lefttomid - 1and store it innode.left. - Build the right subtree from
mid + 1torightand store it innode.right. Both halves leave outmid, which is already in the node. - Return the node so the caller can attach it to its parent. The first call returns the root of the whole tree.
The solution in Java
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length - 1);
}
private TreeNode build(int[] nums, int left, int right) {
if (left > right) {
return null;
}
int mid = (left + right) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = build(nums, left, mid - 1);
node.right = build(nums, mid + 1, right);
return node;
}
}
Java details worth a closer look:
- Why
private. OnlysortedArrayToBSTneedsbuild, so the helper is hidden from other classes. Nothing about the recursion changes if it were public. - References and
null.TreeNodeis a class, sonode.leftandnode.righthold references. A new node starts with both set tonull, and returningnullfrom an empty range simply leaves the matching child empty. - Arrays are shared, not copied. Passing
numstobuildpasses a reference to the same array, so each recursive call reads the original values. The method never writes to the array. - Integer division. In Java,
5 / 2is2, and the same holds for non-negative operands like these indices. The expression(left + right) / 2could overflowintfor arrays close to two billion elements. Writingleft + (right - left) / 2avoids that, but with at most 10,000 elements here, the lesson's form is safe.
Complexity
Time: O(n). Each element becomes exactly one node, created once. Every call does constant work besides its two recursive calls, and the number of calls is at most 2n + 1: one per node plus one per empty child.
Space: O(log n) extra, besides the tree itself. The recursion goes as deep as the tree is tall, and the middle choice keeps the height near log n. The tree's own n nodes are the output and aren't counted as extra.
Edge cases and common mistakes
- One element.
[7]makes a single node. Both recursive calls get an empty range and returnnull. - Two elements.
[1, 3]with this midpoint formula gives1as the root and3as its right child. The mirror-image tree is equally valid. - Even-sized ranges. For
[1, 2, 3, 4]the lower middle,2, becomes the root. Its left child is1and its right subtree is3with4as its right child. The heights of the two sides are 1 and 2, which is balanced. - Using
midagain. Recursing onlefttomidormidtorightrepeats the middle value and, for a one-element range, never shrinks, so the recursion never ends. - Wrong base case. Testing
left == rightinstead ofleft > rightwould returnnullfor single-element ranges and lose values. - Picking the first or last element as root. The tree would still be a valid BST, but it would be a long chain and not height-balanced.
Testing
[-10, -3, 0, 5, 9]gives the tree[0, -10, 5, null, -3, null, 9].[1, 3]gives[1, null, 3], equally valid as[3, 1].[1, 2, 3, 4]gives[2, 1, 3, null, null, null, 4].[5]gives a single node,[5].
