108. Convert Sorted Array to Binary Search Tree
Problem
Turn a sorted array into a height-balanced binary search tree (subtree depths differ by at most 1 at every node). Any such tree is accepted.
Example: [-10,-3,0,5,9] → [0,-3,9,-10,null,5] (or another balanced BST)
Middle element as root keeps the tree height-balanced; recurse on both halves.
Complexity: O(n).
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def build(lo, hi):
if lo > hi:
return None
mid = (lo + hi) // 2
return TreeNode(nums[mid], build(lo, mid - 1), build(mid + 1, hi))
return build(0, len(nums) - 1)
# any height-balanced BST with the same in-order sequence is accepted
def balanced_bst(root, vals):
def walk(n): # (inorder values, height) or None if unbalanced
if not n:
return [], 0
l, r = walk(n.left), walk(n.right)
if l is None or r is None or abs(l[1] - r[1]) > 1:
return None
return l[0] + [n.val] + r[0], 1 + max(l[1], r[1])
w = walk(root)
return w is not None and w[0] == vals
for vals in ([-10, -3, 0, 5, 9], [1, 3], [0], [1, 2, 3, 4, 5, 6, 7, 8]):
assert balanced_bst(Solution().sortedArrayToBST(vals), vals)
class Solution {
public TreeNode sortedArrayToBST(int[] nums) { return build(nums, 0, nums.length - 1); }
private TreeNode build(int[] a, int lo, int hi) {
if (lo > hi) return null;
int mid = (lo + hi) / 2;
return new TreeNode(a[mid], build(a, lo, mid - 1), build(a, mid + 1, hi));
}
}
func sortedArrayToBST(nums []int) *TreeNode {
var build func(lo, hi int) *TreeNode
build = func(lo, hi int) *TreeNode {
if lo > hi {
return nil
}
mid := (lo + hi) / 2 // the middle element keeps both sides balanced
return &TreeNode{Val: nums[mid], Left: build(lo, mid-1), Right: build(mid+1, hi)}
}
return build(0, len(nums)-1)
}