Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #109: Convert Sorted List to Binary Search Tree

In this guide, we solve Leetcode #109 Convert Sorted List to Binary Search Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree. Example 1: Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Tree, Binary Search Tree, Linked List, Divide and Conquer, Binary Tree

Intuition

The input is a tree, so recursive decomposition is a natural fit.

We can compute the answer by combining results from left and right subtrees.

Approach

Use DFS and pass the required state through recursive calls.

Combine child results to compute the answer for each node.

Steps:

  • Pick traversal order.
  • Recurse with state.
  • Combine results from children.

Example

Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Python Solution

# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: def dfs(i: int, j: int) -> Optional[TreeNode]: if i > j: return None mid = (i + j) >> 1 l, r = dfs(i, mid - 1), dfs(mid + 1, j) return TreeNode(nums[mid], l, r) nums = [] while head: nums.append(head.val) head = head.next return dfs(0, len(nums) - 1)

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy