Convert Sorted Array to Binary Search Tree Problem
Description
LeetCode Problem 108.
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
Constraints:
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted in a strictly increasing order.
Solution
Approach: Divide and Conquer on the Middle Element
In a BST, an in-order traversal lists the values in sorted order. So nums is the in-order traversal of the tree we want, and we only have to choose the root of each part.
Choose the middle element as the root. The values to its left are smaller and become the left subtree, the values to its right are larger and become the right subtree. Both halves have the same size, or differ by one, so building each half the same way keeps every node balanced.
build(left, right) builds a tree from nums[left..right]:
- If
left > right, returnnull. - Let
mid = (left + right) / 2and create a node withnums[mid]. - Its left child is
build(left, mid - 1)and its right child isbuild(mid + 1, right).
The answer is build(0, n - 1). Pass indices rather than copies of sub-arrays: copying costs O(n) per level of recursion, O(n log n) in total, while indices keep the whole build O(n).
When the range has an even length there are two middle elements, and either one works. Rounding down, as above, gives [0,-10,5,null,-3,null,9] for the first example; rounding up gives [0,-3,9,-10,null,5]. Both are valid, which is why several outputs are accepted.
Complexity: O(n) time, where n is the length of nums, since each element becomes one node. O(log n) space for the recursion stack, because the tree is balanced (the O(n) output is not counted).
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def build(left: int, right: int) -> Optional[TreeNode]:
"""Builds a balanced BST from nums[left..right]."""
if left > right:
return None
mid = (left + right) // 2 # the middle value becomes the root
root = TreeNode(nums[mid])
root.left = build(left, mid - 1) # smaller values go left
root.right = build(mid + 1, right) # larger values go right
return root
return build(0, len(nums) - 1)
Now write it from memory
Close the write-up and solve it yourself against the tests.