Convert Sorted List to Binary Search Tree

medium linked list divide and conquer bst

Problem

Given a sorted singly linked list, build a height-balanced BST. The list's middle becomes the root; the left half becomes the left subtree and the right half becomes the right subtree.

Inputhead = -10 → -3 → 0 → 5 → 9
Outputbalanced BST rooted at 0
Use slow/fast to find the middle of each sublist in O(n) per level → O(n log n) total.

def sortedListToBST(head):
    def build(head, tail):
        if head is tail: return None
        slow = fast = head
        while fast is not tail and fast.next is not tail:
            slow = slow.next
            fast = fast.next.next
        node = TreeNode(slow.val)
        node.left = build(head, slow)
        node.right = build(slow.next, tail)
        return node
    return build(head, None)
function sortedListToBST(head) {
  function build(h, tail) {
    if (h === tail) return null;
    let slow = h, fast = h;
    while (fast !== tail && fast.next !== tail) {
      slow = slow.next;
      fast = fast.next.next;
    }
    const node = new TreeNode(slow.val);
    node.left = build(h, slow);
    node.right = build(slow.next, tail);
    return node;
  }
  return build(head, null);
}
class Solution {
    public TreeNode sortedListToBST(ListNode head) { return build(head, null); }
    TreeNode build(ListNode head, ListNode tail) {
        if (head == tail) return null;
        ListNode slow = head, fast = head;
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode node = new TreeNode(slow.val);
        node.left = build(head, slow);
        node.right = build(slow.next, tail);
        return node;
    }
}
class Solution {
public:
    TreeNode* build(ListNode* head, ListNode* tail) {
        if (head == tail) return nullptr;
        ListNode* slow = head; ListNode* fast = head;
        while (fast != tail && fast->next != tail) {
            slow = slow->next;
            fast = fast->next->next;
        }
        TreeNode* node = new TreeNode(slow->val);
        node->left = build(head, slow);
        node->right = build(slow->next, tail);
        return node;
    }
    TreeNode* sortedListToBST(ListNode* head) { return build(head, nullptr); }
};
Time: O(n log n) Space: O(log n) recursion