Problem overview
The method sortedArrayToBST receives a list nums of integers sorted in strictly increasing order. It must return the root of a height-balanced binary search tree that holds exactly those values. Height-balanced means that for every node, the heights of its left and right subtrees differ by at most one.
In the first example, nums = [-10, -3, 0, 5, 9]. One valid answer has 0 at the root, with -10 and 5 below it, and -3 and 9 below those. Its level-order form is [0, -10, 5, None, -3, None, 9]. Other balanced trees are accepted too, such as [0, -3, 9, -10, None, 5], because many shapes satisfy the rules. In the second example, [1, 3], either value can be the root.
Approach: the middle element becomes the root
A binary search tree keeps smaller values in the left subtree and larger values in the right subtree. Because nums is already sorted, every value before a given position is smaller than the value at that position, and every value after it is larger. So if you pick any element as the root, the elements to its left in the list must form the left subtree, and the elements to its right must form the right subtree. The ordering rule is satisfied automatically.
What decides the balance is which element you pick. Choosing the first or last element puts everything on one side and produces a chain, a tree as tall as the list is long. Choosing the middle element splits the rest into two halves of nearly equal size. Do the same inside each half, and every node has two subtrees whose sizes differ by at most one, which keeps their heights within one of each other as well.
This is a natural recursion: build a tree from a range of the list by choosing its middle element, then build the left subtree from the part before it and the right subtree from the part after it. A range with no elements produces no node, which is the base case.
The lesson passes the range as two indices, left and right, instead of slicing the list. A slice such as nums[:mid] copies its elements, so slicing at every level would copy the list again and again. With indices, every call reads the same list.
Step by step
- Start the recursion from
sortedArrayToBST. It calls the helperbuildwith the whole list: start index 0 and last indexlen(nums) - 1. Both bounds are inclusive. - Define
buildwith the range as parameters.leftandrightsay which part ofnumsthis call is responsible for. Becausebuildis a method, it is called asself.build(...), including in the recursive calls. - Stop on an empty range. When
left > rightthere are no elements left, so the call returnsNone. This case occurs even for a non-empty input: a range holding one element splits into two empty ranges. - Find the middle index as
(left + right) // 2. The//operator divides and rounds down, somidis a whole number you can use as a list index. - Create the node from
nums[mid]. This is the root of the subtree for this range. - Build the left subtree from
lefttomid - 1and attach it asnode.left. - Build the right subtree from
mid + 1torightand attach it asnode.right. Both ranges skipmid, because that value is already innode. - Return
nodeso the caller can attach it to its own parent. The first call returns the root of the whole tree.
The solution in Python
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
return self.build(nums, 0, len(nums) - 1)
def build(self, nums, left, right):
if left > right:
return None
mid = (left + right) // 2
node = TreeNode(nums[mid])
node.left = self.build(nums, left, mid - 1)
node.right = self.build(nums, mid + 1, right)
return node
The Python details worth a closer look:
- Floor division picks the left middle. For a range of even length, there are two middle positions. With
left = 0andright = 1,(0 + 1) // 2is 0, so the lower one is the root. For[1, 3]the result is the tree[1, None, 3], which the statement lists as valid. Using plain/would produce a float such as0.5, and a list index must be an integer, so it would raise aTypeError. - No overflow worry. Python integers have no fixed size, so
left + rightcan't overflow. Languages with fixed-width integers sometimes writeleft + (right - left) // 2instead. - A
TreeNodeis an ordinary object. Its constructor takes the value, andleftandrightstart asNone. Assigning tonode.leftandnode.rightafterwards links the children. - Self-calls need
self. Inside a class,build(nums, ...)on its own would raise aNameError. The method is reached through the instance, asself.build. - The return type.
Optional[TreeNode]means the result is aTreeNodeorNone. The helper returnsNonefor an empty range, and that value becomes a missing child.
Complexity
Time: O(n). Each element is the middle of exactly one range, so build creates exactly one node per element. The calls that return None do constant work, and there are n + 1 of them. The total is proportional to n.
Space: O(log n) extra, not counting the tree. The tree itself needs n nodes, which the task requires. Besides that, the only memory is the recursion stack. Each call halves the range, so the depth is about log2(n). For 10,000 elements that is around 14 levels, far below Python's default recursion limit of 1000. Slicing instead of using indices would add O(n) copying work per level.
Edge cases and common mistakes
- One element.
[7]makes a single node with no children: both recursive calls get an empty range and returnNone. - Two elements. One value becomes the root and the other its only child. Both choices are balanced.
- Using
left >= rightas the base case. A range with one element hasleft == right, so that element would be dropped. Onlyleft > rightmeans the range is empty. - Including
midagain. Callingbuild(nums, left, mid)would never shrink a one-element range, and the recursion would not end. - Picking an end element. Always choosing
leftas the root makes a valid BST, but it is a chain of lengthn, not a balanced tree. - Several correct answers. A tree different from the one in an example can still be right. For six elements, this solution gives
[3, 1, 5, None, 2, 4, 6]in level order. Check the properties (sorted in-order values, heights within one), not one fixed shape.
Testing
nums = [-10, -3, 0, 5, 9]gives level order[0, -10, 5, None, -3, None, 9].nums = [1, 3]gives[1, None, 3].nums = [7]gives[7].nums = [1, 2, 3, 4, 5, 6]gives[3, 1, 5, None, 2, 4, 6].- A list of 10,000 consecutive integers gives a tree of height 14.
