Convert Sorted List to BST — Fast/Slow + Recursion
Advertisement
Problem 243 · Convert Sorted List to Binary Search Tree
Difficulty: Medium · Pattern: Fast/Slow + Recursive Divide
Find middle → root. Left half → left subtree. Right half → right subtree.
Solutions
# Python
def sortedListToBST(head):
if not head: return None
if not head.next: return TreeNode(head.val)
# Find middle and disconnect left half
slow = head; fast = head; prev = None
while fast and fast.next:
prev = slow; slow = slow.next; fast = fast.next.next
if prev: prev.next = None # disconnect left half
root = TreeNode(slow.val)
root.left = sortedListToBST(head if prev else None)
root.right = sortedListToBST(slow.next)
return root
// Java
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow; slow = slow.next; fast = fast.next.next;
}
if (prev != null) prev.next = null;
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(prev != null ? head : null);
root.right = sortedListToBST(slow.next);
return root;
}
Complexity
- Time: O(n log n)
- Space: O(log n) recursive stack
Advertisement