SDE & MLE Prep

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)