Problem overview
The method sortedArrayToBST receives nums, an array of integers sorted in strictly ascending order, and returns the root of a height-balanced binary search tree (BST) holding exactly those values. Height-balanced means that for every node, the depths of its left and right subtrees differ by at most one. In a BST, every value in a node's left subtree is smaller than the node's value and every value in its right subtree is larger.
For [-10, -3, 0, 5, 9] one valid answer has 0 at the root, with -10 and -3 on the left and 5 and 9 on the right. The statement shows it as [0, -10, 5, null, -3, null, 9] in level order. For [1, 3] both [3, 1] and [1, null, 3] are balanced BSTs, so more than one answer can be correct.
Approach: the middle element becomes the root
A sorted array already contains the inorder traversal of a BST: reading a BST left subtree, then node, then right subtree gives its values in ascending order. So the job is to choose a root and let the array split itself around it. Everything before the root in the array goes to the left subtree, and everything after it goes to the right.
The choice of root decides the shape. Take the first element every time and the tree becomes a chain leaning right, with a depth equal to the array length. Take the middle element and the two sides have almost equal sizes. Apply the same rule to each side and every node splits its range roughly in half, so the depths of its two subtrees can differ by at most one.
The idea is recursive: build the tree for a range by taking its middle element as the root, then building the left subtree from the part on its left and the right subtree from the part on its right. A range with no elements produces no node, which is null.
The recursion passes two indexes into the same array instead of cutting out smaller arrays with slice. A slice copies its elements, so slicing at every level would copy a lot of data. With indexes, every call shares one array and does constant work of its own.
Step by step
- Start from the main method.
sortedArrayToBSTcalls a helper namedbuildthroughthis.buildwith the whole array, the first index0and the last index,nums.length - 1. Both ends are inclusive. - Declare
build(nums, left, right)as a second method of the class. The two indexes mark the part ofnumsthat this call turns into a subtree. - Write the base case. When
left > right, the range has no elements. This happens even for non-empty input: when a range has one element, both of its halves are empty. - Return
nullfor the empty range. It means "no node here" and also ends the recursion. Without it, the calls would keep going forever. - Find the middle index.
(left + right) / 2can be fractional in JavaScript, because/does not do integer division.Math.floorrounds it down to a whole index. - Create the node with
new TreeNode(nums[mid]). This is the root of the current subtree. - Build the left subtree from
lefttomid - 1and assign it tonode.left. Every value there is smaller thannums[mid], as the BST rule needs. - Build the right subtree from
mid + 1torightand assign it tonode.right. Both ranges skipmid, since that value is already innode. - Return
nodeso the caller can attach the finished subtree to its parent. The first call returns the root of the whole tree.
On [-10, -3, 0, 5, 9]: the first call has range 0 to 4, so mid = 2 and the root is 0. The left call has range 0 to 1, so mid = 0 and the node is -10, whose left side is empty and whose right side, the range 1 to 1, becomes the node -3. The right call has range 3 to 4, so mid = 3 and the node is 5, with 9 as its right child. That is exactly the tree from the example.
The solution in JavaScript
class Solution {
sortedArrayToBST(nums) {
return this.build(nums, 0, nums.length - 1);
}
build(nums, left, right) {
if (left > right) {
return null;
}
const mid = Math.floor((left + right) / 2);
const node = new TreeNode(nums[mid]);
node.left = this.build(nums, left, mid - 1);
node.right = this.build(nums, mid + 1, right);
return node;
}
}
JavaScript details worth knowing:
- Methods call each other through
this. Inside a class, writingbuild(...)alone would look for a variable or a global function namedbuildand fail. Methods of the same object are reached asthis.build(...). The recursive calls work because they are written asthis.buildand are made from a method called on the instance. Math.flooron the midpoint. Indexing an array with a fractional number such asnums[1.5]givesundefined, not an error, so a missing floor would build nodes withundefinedvalues. The sumleft + rightcannot overflow here: JavaScript numbers are doubles and the indexes are at most 9,999.- Which middle is chosen. For an even count the floor picks the left of the two middle elements. That is why
[1, 3]gives a root of 1 with 3 as its right child. The statement accepts this shape. TreeNodeis supplied. The lesson provides the class, with the value passed to the constructor andleftandrightstarting asnull.- Returning
nullexplicitly. A function that falls off its end returnsundefined, notnull. Tree code should returnnullfor "no child" so that all missing children look the same.
Complexity
Time: O(n). Every element becomes exactly one node, created in one call of build. Each non-empty call creates one node and makes two more calls, so there are n calls with a node and at most n + 1 calls that hit the empty base case. Each call does constant work, because it passes indexes and copies nothing.
Space: O(log n) beyond the output. The tree itself takes O(n), but that is the result. The extra memory is the recursion stack, whose depth equals the tree height. Halving the range at each level keeps the height near log₂ n: for 10,000 elements it is 14. A deep stack is never a risk here, which would not be true if the split were uneven.
Edge cases and common mistakes
- One element.
[7]gives a single node. Both recursive calls get an empty range and returnnull. - Two elements. One of them becomes the root and the other its only child, which is still balanced because the depths differ by one.
- Off-by-one at the ends. The helper takes inclusive bounds, so the first call must pass
nums.length - 1, notnums.length. Passing the length would readnums[nums.length], which isundefined. - Including
midin a half. Recursing onlefttomidormidtorightrepeats a value and, for a one-element range, never shrinks the range, so the recursion never ends. - Choosing an end element as the root. It still produces a valid BST, but a chain, and a chain is not height-balanced.
- Using
slicein the recursion. Copying the halves keeps the logic correct but adds anO(n)copy at each level, which turns the total intoO(n log n)time.
Testing
Level-order lists, with null for missing children:
[-10, -3, 0, 5, 9]gives[0, -10, 5, null, -3, null, 9].[1, 3]gives[1, null, 3], one of the two accepted answers.[7]gives[7].[1, 2, 3, 4, 5, 6]gives[3, 1, 5, null, 2, 4, 6].
