Problem overview
The method sortedArrayToBST receives a vector nums sorted in strictly increasing order and returns the root of a binary search tree (BST) holding exactly those values. The tree must be height-balanced: for every node, the heights of its left and right subtrees differ by at most one.
For nums = [-10, -3, 0, 5, 9] one valid answer has 0 at the root, -10 with a right child -3 on the left, and 5 with a right child 9 on the right. Several trees can be correct, and a different shape that is still balanced and ordered is accepted too. For [1, 3], both 3 with a left child 1, and 1 with a right child 3, are valid.
Approach: the middle element becomes the root
A BST needs every value in a node's left subtree to be smaller than the node and every value in its right subtree to be larger. In a sorted array that is easy to satisfy: pick any element as the root, and everything to its left in the array is smaller, everything to its right is larger. The left part then becomes the left subtree, and the right part the right subtree, each built the same way.
That gives the recursion, but the choice of root decides the balance. If you always pick the first element, every node has only a right child and the tree is a linked list of height n. If you pick the middle element, the two halves differ in size by at most one, and the same holds at every level below. The heights then differ by at most one everywhere, so the tree is balanced.
Take [1, 2, 3, 4, 5, 6]. The middle index of 0..5 is 2, so the root is 3. The left half [1, 2] has middle index 0, so 1 is the left child, and 2 hangs to its right. The right half [4, 5, 6] has 5 as its root with children 4 and 6.
Step by step
- Delegate in
sortedArrayToBST. Call a helper namedbuildwith the vector, the first index 0 and the last indexnums.size() - 1. Passing index bounds lets every call work on the same vector without copying parts of it. - Declare
build. It returns aTreeNode*and takes the vector by reference plus twointparameters,leftandright, the inclusive range this call is responsible for. - Base case. If
left > right, the range is empty. Returnnullptr, which means "no child here". This is what ends the recursion: a one-element range splits into two empty ones. - Find the middle.
mid = (left + right) / 2. Integer division drops the fraction, so for an even-sized range this picks the left of the two middle elements. - Create the node with
new TreeNode(nums[mid]). It is allocated on the heap because the tree must outlive this function call. - Build the left subtree from
lefttomid - 1and store it innode->left. - Build the right subtree from
mid + 1torightand store it innode->right. Both ranges skipmid, because that value is already innode. - Return
nodeso the caller can attach it to its parent. The first call's result is the root of the whole tree.
The solution in C++
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return build(nums, 0, nums.size() - 1);
}
TreeNode* build(vector<int>& nums, int left, int right) {
if (left > right) {
return nullptr;
}
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;
}
};
The C++ details to notice:
TreeNode*andnew. A localTreeNodeobject would be destroyed whenbuildreturns, leaving the parent with a dangling pointer.newcreates the node on the heap, where it stays until it is deleted. Here the caller owns the whole tree. In a real program you would free it withdeleteor use smart pointers.- Arrow syntax.
nodeis a pointer, so its fields are reached with->.node->leftis shorthand for(*node).left. nullptr. It is the type-safe null pointer. A leaf hasleftandrightequal tonullptr, and the base case returns it for every empty range.- Pass by reference. The parameter
vector<int>& numsavoids copying the vector at each of the roughlynrecursive calls. Copying would make the algorithm quadratic. nums.size() - 1.size()returns an unsigned type, and the value is converted tointwhen it is passed toright. That is fine for sizes up to 10,000. On an empty vector,size() - 1wraps around to the largest unsigned value, and the conversion tointgives -1 on common platforms. The lesson guarantees at least one element.- The midpoint.
(left + right) / 2could overflowintfor indices near two billion. With at most 10,000 elements it can't, butleft + (right - left) / 2is the habit that is always safe. - Member function order. Inside a class,
sortedArrayToBSTcan callbuildeven thoughbuildis defined below it. Member function bodies are compiled once the whole class has been seen.
Complexity
Time: O(n). Each call creates exactly one node and then makes two further calls. Every element becomes the middle of exactly one range, so there are n nodes created and n + 1 calls that hit the base case. The work per call is constant.
Space: O(log n) extra, not counting the tree itself. The recursion goes as deep as the height of the tree, and halving the range each time keeps that near log2(n). The tree has n nodes, which is the output.
Edge cases and common mistakes
- A single element. The range 0..0 gives a node with two
nullptrchildren, each coming from a range withleft > right. - Two elements. For
[1, 3]the middle is index 0, so the root is 1 and 3 is its right child. That shape is accepted, and so is the mirror image. - Off-by-one in the halves. Recursing on
left..midinstead ofleft..mid - 1never shrinks a one-element range and the recursion never ends. Skippingmidon both sides is what guarantees progress. - Base case with
==. Checkingleft == rightas the stopping case misses the empty ranges that appear whenmidis at either end. Useleft > right. - Slicing the vector. Building new vectors for each half works but copies elements at every level, which costs
O(n log n)time. Index bounds avoid it. - Choosing the first or last element as the root. The result is still a valid BST, but a chain, so it fails the balance requirement.
Testing
Printing the tree in pre-order (node, left, right) with null for a missing child gives these results:
[-10, -3, 0, 5, 9]gives0 -10 null -3 null null 5 null 9 null null.[1, 3]gives1 null 3 null null.[7]gives7 null null.[1, 2, 3, 4, 5, 6]gives3 1 null 2 null null 5 4 null null 6 null null.
