Problem 109

Abstract / Summary

Given a sorted linked list convert it into a height balanced binary search tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0109.py

class Solution:
    def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
        # flatten
        all = []
        while head:
            all.append(head.val)
            head = head.next

        # divide'n'conquer
        def deeper(left, right):
            if left > right:
                return None

            pivot = (left + right) // 2
            return TreeNode(all[pivot], deeper(left, pivot - 1), deeper(pivot + 1, right))

        return deeper(0, len(all) - 1)
17 lines | 519 bytes | submitted August 31, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Search Tree
  • Binary Tree
  • Divide And Conquer
  • Linked List
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation converts a sorted singly-linked list into a height-balanced binary search tree (BST). It follows a two-phase strategy: first it extracts the list values into an array, then it builds the BST recursively by selecting the middle element of each sub-array as the root. The approach guarantees that the resulting tree is balanced because the middle element is always chosen as the pivot for each recursive subdivision.

Flattening the linked list

The initial phase traverses the input list node-by-node, appending each node’s value to a plain Python list named all. This linear pass collects the sorted values while discarding the original node structure.

all = []
while head:
    all.append(head.val)
    head = head.next

By the end of this loop, all contains the entire sequence of values in ascending order, ready for random access during the tree construction.

Recursive construction

A nested helper function deeper receives two indices, left and right, that delimit the current segment of the array to be turned into a subtree. The base case occurs when left exceeds right, in which case the function returns None, indicating an empty subtree.

def deeper(left, right):
    if left > right:
        return None

When the segment is non-empty, the midpoint is computed with integer division, and a new TreeNode is instantiated using the value at that midpoint. The left and right children are produced by recursive calls on the left and right sub-segments, respectively.

pivot = (left + right) // 2
return TreeNode(all[pivot], deeper(left, pivot - 1), deeper(pivot + 1, right))

The outer call initiates the recursion with the full range of the array:

return deeper(0, len(all) - 1)

Because each recursive call reduces the segment size roughly by half, the tree is built in a balanced fashion, mirroring the structure of a binary search tree derived from a sorted array.

Edge case handling

The algorithm gracefully handles an empty input list. In that scenario, the initial while-loop never executes, leaving all as an empty list. The subsequent call to deeper(0, -1) immediately satisfies the left > right condition, causing the function to return None. Consequently, the overall result is a None tree, correctly representing the absence of nodes.

When the list contains a single element, the array all holds one item. The first call to deeper receives left = 0 and right = 0. The midpoint calculation yields pivot = 0, and a TreeNode is created with that sole value. Both recursive calls for the left and right children receive ranges where left > right, so they return None. The final tree consists of a single node, satisfying the balanced BST property.

Performance considerations

The conversion benefits from two key optimizations. First, the flattening step stores values in a contiguous list, enabling O(1) random access to any element. This eliminates the need to traverse the linked list repeatedly during tree construction, which would otherwise increase the overall work.

Second, the recursive builder works directly on index boundaries rather than slicing the array. By passing integer indices (left and right) instead of creating new sub-lists, the implementation avoids the overhead of copying data for each recursive call. This in-place approach reduces memory churn and improves cache locality, as the same underlying list is accessed throughout the recursion.

Together, these choices ensure that the algorithm runs efficiently, constructing the balanced BST with a single pass to collect values followed by a depth-first recursion that visits each array element exactly once.

written by openai gpt

ELI5 - Simplified Explanation

Imagine that a long train of numbered cars is waiting on a track. The first part of this code walks along the track and writes down every number it sees, one by one, until it reaches the end of the train. Now there is a neat list of numbers sitting on a sheet of paper.

The second part of the code is like building a balanced tree structure out of those numbers. It looks at the list and picks the middle number to be the very top of the tree. Everything to the left of that middle number goes into a smaller branch on the left side, and everything to the right goes into a branch on the right side.

The code then repeats this trick for each new branch, always picking the middle number to keep the tree perfectly even and tidy. This continues until every number from the train has a special spot in the tree. It is a very clever way to turn a long line into a beautiful, organized shape.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.26 | σ = 0.64

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS Go C TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
52 links | 35 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Convert Sorted List to Binary Search Tree | Google | Flipkart | Amazon | Leetcode 109'
codestorywithMIK 23 mins
Convert Sorted List to Binary Search Tree | Google | Flipkart | Amazon | Leetcode 109
YouTube video 'Convert Sorted List to Binary Search Tree (BST) | LeetCode 109 | C++, Java, Python'
Knowledge Center 19 mins
Convert Sorted List to Binary Search Tree (BST) | LeetCode 109 | C++, Java, Python
YouTube video 'Convert Binary Search Tree to Sorted Doubly Linked List || Leetcode 426 || Big Tech Variant Question'
Coding with Minmer 17 mins
Convert Binary Search Tree to Sorted Doubly Linked List || Leetcode 426 || Big Tech Variant Question
YouTube video 'LeetCode 109. Convert Sorted List to Binary Search Tree'
Happy Coding 14 mins
LeetCode 109. Convert Sorted List to Binary Search Tree
YouTube video 'Convert Sorted List to Binary Search Tree | Leetcode 108, 109 | Facebook Microsoft | BST'
Naresh Gupta 14 mins
Convert Sorted List to Binary Search Tree | Leetcode 108, 109 | Facebook Microsoft | BST
YouTube video 'LeetCode 109 Convert Sorted List to Binary Search Tree'
Jeevan Kumar - Cracckify 6 mins
LeetCode 109 Convert Sorted List to Binary Search Tree
YouTube video '109 || Convert Sorted List to Binary Search Tree II || C++ || Leetcode Daily Challenge'
CodeFreaks 12 mins
109 || Convert Sorted List to Binary Search Tree II || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #1075: Mar 11, 2023 - 109. Convert Sorted List to Binary Search Tree'
Programming Live with Larry 18 mins
Daily Leetcode #1075: Mar 11, 2023 - 109. Convert Sorted List to Binary Search Tree
YouTube video 'Leetcode [109] Convert Sorted list to Binary Search Tree'
SDE Skills 26 mins
Leetcode [109] Convert Sorted list to Binary Search Tree
YouTube video 'Convert Sorted List to Binary Search Tree - Leetcode 109 - Python'
Lit Code 7 mins
Convert Sorted List to Binary Search Tree - Leetcode 109 - Python
YouTube video 'Convert Sorted List to Binary Search Tree | LeetCode 109 | Coders Camp'
Coders Camp 11 mins
Convert Sorted List to Binary Search Tree | LeetCode 109 | Coders Camp
YouTube video 'Daily Leetcode #401: May 06, 2021 - 109. Convert Sorted List to Binary Search Tree'
Programming Live with Larry 15 mins
Daily Leetcode #401: May 06, 2021 - 109. Convert Sorted List to Binary Search Tree
YouTube video '109. Convert Sorted List to Binary Search Tree | O(n) TC | Binary Tree | Linked List |LeetCode Daily'
LeetCodeWithMonu 14 mins
109. Convert Sorted List to Binary Search Tree | O(n) TC | Binary Tree | Linked List |LeetCode Daily
YouTube video '109. Convert Sorted List to Binary Search Tree | Leetcode | Binary Search Tree | DSA'
Coding with Tamilarasan 5 mins
109. Convert Sorted List to Binary Search Tree | Leetcode | Binary Search Tree | DSA
YouTube video 'Leetcode 109 [MS/Meta]. Convert Sorted List to Binary Search Tree - slow-fast pointers and recursion'
Code-Yao 11 mins
Leetcode 109 [MS/Meta]. Convert Sorted List to Binary Search Tree - slow-fast pointers and recursion
YouTube video '109  Convert Sorted List to Binary Search Tree'
Math Geeks 3 mins
109 Convert Sorted List to Binary Search Tree
YouTube video '109. Convert Sorted List to Binary Search Tree | Leetcode | Python'
Abdullah Arshed 8 mins
109. Convert Sorted List to Binary Search Tree | Leetcode | Python
YouTube video 'leetcode 109. Convert Sorted List to Binary Search Tree - recursion,  work with array or linked list'
Code-Yao 17 mins
leetcode 109. Convert Sorted List to Binary Search Tree - recursion, work with array or linked list
YouTube video 'LeetCode 109 | Convert Sorted List to Binary Search Tree | Recursion | Java'
Sleepy Cracker 4 mins
LeetCode 109 | Convert Sorted List to Binary Search Tree | Recursion | Java
YouTube video 'Convert Sorted List to Binary Search Tree | Leetcode 109 | Approach + Code with explanation.'
Pirai's Academy 12 mins
Convert Sorted List to Binary Search Tree | Leetcode 109 | Approach + Code with explanation.
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality