109. Convert Sorted List to Binary Search Tree
Problem
Turn a sorted singly linked list into a height-balanced binary search tree. Any balanced BST with the same values is accepted.
Example: -10→-3→0→5→9 → [0,-3,9,-10,null,5] (or another balanced BST)
Constraints: up to 2·10⁴ nodes.
Count the nodes, then build the tree in in-order: recursively build the left half, consume the current list node as root, build the right half. The list pointer advances exactly in sorted order → O(n).
Complexity: O(n) time, O(log n) stack.
class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
n, p = 0, head
while p:
n, p = n + 1, p.next
cur = head
def build(lo, hi):
nonlocal cur
if lo > hi:
return None
mid = (lo + hi) // 2
left = build(lo, mid - 1)
root = TreeNode(cur.val, left)
cur = cur.next
root.right = build(mid + 1, hi)
return root
return build(0, n - 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().sortedListToBST(make_list(vals)), vals)
assert Solution().sortedListToBST(None) is None
class Solution {
private ListNode cur;
public TreeNode sortedListToBST(ListNode head) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) n++;
cur = head;
return build(0, n - 1);
}
private TreeNode build(int lo, int hi) {
if (lo > hi) return null;
int mid = (lo + hi) / 2;
TreeNode left = build(lo, mid - 1);
TreeNode root = new TreeNode(cur.val);
cur = cur.next;
root.left = left;
root.right = build(mid + 1, hi);
return root;
}
}
func sortedListToBST(head *ListNode) *TreeNode {
n := 0
for p := head; p != nil; p = p.Next {
n++
}
cur := head // consumed in order while building in-order
var build func(lo, hi int) *TreeNode
build = func(lo, hi int) *TreeNode {
if lo > hi {
return nil
}
mid := (lo + hi) / 2
left := build(lo, mid-1)
root := &TreeNode{Val: cur.Val, Left: left}
cur = cur.Next
root.Right = build(mid+1, hi)
return root
}
return build(0, n-1)
}