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)
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 108: Convert Sorted Array to Binary Search Tree
- problem 2196: Create Binary Tree From Descriptions
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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