Problem 108

Abstract / Summary

Given a sorted list of numbers create a balanced binary search tree from it.

Note

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

Python 0108.py

class Solution:
    def add(self, nums, begin, end):
        if not nums or begin >= end:
            return None

        mid = (begin + end) // 2
        left  = self.add(nums, begin, mid)
        right = self.add(nums, mid + 1, end)
        return TreeNode(nums[mid], left, right)

    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        return self.add(nums, 0, len(nums))
12 lines | 412 bytes | submitted August 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search Tree
  • Binary Tree
  • Divide And Conquer
  • 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 integer array into a height-balanced binary search tree (BST). The conversion is performed by a recursive helper method that selects the middle element of a sub-range as the root, then recursively builds left and right sub-trees from the left and right halves of the range. The public entry point simply invokes this helper with the full range of the input list.

Recursive Construction

The heart of the algorithm lies in the add method. It receives the original list together with two integer indices that delimit the current sub-range. The method first checks for termination conditions: an empty list or a range where the start index is not less than the end index. In those cases it returns None, which signals that a leaf node has been reached.

def add(self, nums, begin, end):
    if not nums or begin >= end:
        return None

When the range is valid, the midpoint is computed using integer division. This midpoint determines the value that becomes the root of the current subtree. By using integer division, the algorithm consistently picks the lower middle element for even-length ranges, which preserves the balanced property.

    mid = (begin + end) // 2

The left subtree is constructed by recursively calling add on the segment that lies before the midpoint, while the right subtree is built from the segment that follows the midpoint. The recursion naturally terminates when the sub-range collapses, producing None for missing children.

    left  = self.add(nums, begin, mid)
    right = self.add(nums, mid + 1, end)

Finally, a new TreeNode instance is created with the midpoint value and the previously built left and right children. This node is returned up the call stack, gradually assembling the full BST.

    return TreeNode(nums[mid], left, right)

Public Interface

The sortedArrayToBST method serves as the entry point for callers. It forwards the original list along with the start index 0 and the exclusive end index len(nums) to the recursive helper. By using an exclusive end index, the method avoids off-by-one errors and aligns with Python’s slicing conventions, even though slicing is not performed directly.

def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
    return self.add(nums, 0, len(nums))

Edge Cases Handled

The code explicitly checks for an empty input list. When nums is empty, the guard if not nums triggers, causing the helper to return None. This ensures that the public method returns None for an empty array, representing an empty tree.

Another edge condition is when the begin index meets or exceeds the end index. This situation occurs when a sub-range has been reduced to zero elements, which is the natural base case for recursion. By returning None in this scenario, the algorithm correctly terminates the branch without attempting to access out-of-range elements.

The midpoint calculation using integer division gracefully handles both odd and even sized sub-ranges. For an even number of elements, the lower middle index is chosen, which still yields a balanced tree because the sizes of the left and right sub-ranges differ by at most one element.

Performance Optimizations

The implementation avoids creating new list slices for each recursive call. Instead of passing sub-lists, it passes index boundaries that reference the original list. This approach eliminates the overhead of copying data and reduces memory pressure, especially for large input arrays.

By selecting the middle element as the root at each step, the algorithm guarantees that the depth of the tree grows logarithmically relative to the number of elements. This balanced construction prevents the formation of degenerate (linear) trees, which would degrade operations that rely on tree height.

The recursion depth is bounded by the height of the resulting tree. Because the tree is balanced, the recursion stack remains shallow, which minimizes the risk of stack overflow for typical input sizes.

The use of a single TreeNode constructor call per node ensures that node creation is performed exactly once per element, avoiding redundant allocations. The left and right child references are assigned directly from the results of the recursive calls, which streamlines the assembly of the tree structure.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big pile of numbers organized in a perfect line from smallest to largest. To turn this line into a special tree shape, pick the number right in the middle to be the crown at the top. Everything to the left of that middle spot becomes the left branch, and everything to the right becomes the right branch. Now, just repeat that same trick for each new branch. You keep picking the middle of the smaller lines until every single number has its own place in the tree. It is like building a tower by always finding the center point to keep everything balanced and tidy.

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.07 | σ = 1.39

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 C# JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM Java
varunu28 Java
vli02 C
vthwang Java
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
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM Java
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
59 links | 42 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Convert Sorted Array to Binary Search Tree - Leetcode 108 - Python'
NeetCode 10 mins
Convert Sorted Array to Binary Search Tree - Leetcode 108 - Python
YouTube video 'Convert Sorted Array to Binary Search Tree (LeetCode 108. Algorithm Explained)'
Nick White 10 mins
Convert Sorted Array to Binary Search Tree (LeetCode 108. Algorithm Explained)
YouTube video '[Java] Leetcode 108. Convert Sorted Array to Binary Search Tree [Binary Search Tree #1]'
Eric Programming 6 mins
[Java] Leetcode 108. Convert Sorted Array to Binary Search Tree [Binary Search Tree #1]
YouTube video 'LeetCode 108. Convert Sorted Array to Binary Search Tree - Interview Prep Ep 71'
Fisher Coder 9 mins
LeetCode 108. Convert Sorted Array to Binary Search Tree - Interview Prep Ep 71
YouTube video 'Convert Sorted Array to Binary Search Tree | LeetCode 108 | Theory + Python'
Sai Anish Malla 9 mins
Convert Sorted Array to Binary Search Tree | LeetCode 108 | Theory + Python
YouTube video '108. Convert Sorted Array to Binary Search Tree | LEETCODE EASY | TREE | CODE EXPLAINER'
code Explainer 10 mins
108. Convert Sorted Array to Binary Search Tree | LEETCODE EASY | TREE | CODE EXPLAINER
YouTube video 'Convert Sorted Array to Binary Search Tree | Leetcode 108 | Live coding session'
Coding Decoded 6 mins
Convert Sorted Array to Binary Search Tree | Leetcode 108 | Live coding session
YouTube video 'Convert Sorted Array or List to Binary Search Tree | LeetCode Java Solutions | Geekific'
Geekific 5 mins
Convert Sorted Array or List to Binary Search Tree | LeetCode Java Solutions | Geekific
YouTube video 'Can You Convert Array Into a Tree? (LeetCode 108: Convert Sorted Array to Binary Search Tree)'
Code With Zi 7 mins
Can You Convert Array Into a Tree? (LeetCode 108: Convert Sorted Array to Binary Search Tree)
YouTube video 'How To Convert A Sorted Array To A Binary Search Tree - LeetCode 108'
Michael Vandi 11 mins
How To Convert A Sorted Array To A Binary Search Tree - LeetCode 108
YouTube video 'Convert Sorted Array to Binary Search Tree - Leetcode 108 - Java'
Code With K5KC 6 mins
Convert Sorted Array to Binary Search Tree - Leetcode 108 - Java
YouTube video '108. Convert Sorted Array To Binary Search Tree (Leetcode Easy)'
Programming Live with Larry 17 mins
108. Convert Sorted Array To Binary Search Tree (Leetcode Easy)
YouTube video 'Daily Leetcode #862: Aug 10, 2022 - 108. Convert Sorted Array to Binary Search Tree'
Programming Live with Larry 4 mins
Daily Leetcode #862: Aug 10, 2022 - 108. Convert Sorted Array to Binary Search Tree
YouTube video '108. Convert Sorted Array to Binary Search Tree | Leetcode | Cpp | Java | Python'
Komal Pal 20 mins
108. Convert Sorted Array to Binary Search Tree | Leetcode | Cpp | Java | Python
YouTube video 'Convert Sorted Array to Binary Search Tree | Algorithm Explained | LeetCode 108 | Learn Overflow'
Learn Overflow 13 mins
Convert Sorted Array to Binary Search Tree | Algorithm Explained | LeetCode 108 | Learn Overflow
YouTube video 'Leetcode 108: Convert Sorted Array to Binary Search Tree'
Algorithms Casts 8 mins
Leetcode 108: Convert Sorted Array to Binary Search Tree
YouTube video 'Day 260: LeetCode Problem 108. Convert Sorted Array to Binary Search Tree - Swift'
iOSxBank 10 mins
Day 260: LeetCode Problem 108. Convert Sorted Array to Binary Search Tree - Swift
YouTube video 'Convert Sorted Array to Binary Search Tree | Amazon Interview Question | Tree | LeetCode 108 | C++'
Programming With Niladree - PWN - Bangladesh 5 mins
Convert Sorted Array to Binary Search Tree | Amazon Interview Question | Tree | LeetCode 108 | C++
YouTube video 'Convert Sorted Array to Binary Search Tree | 108 | JavaScript Recursive Solution | LeetCode 101'
Software Interviews Prep 9 mins
Convert Sorted Array to Binary Search Tree | 108 | JavaScript Recursive Solution | LeetCode 101
YouTube video 'Convert Sorted Array to Binary Search Tree | Leetcode 108 | Approach + Code with explanation.'
Pirai's Academy 12 mins
Convert Sorted Array to Binary Search Tree | Leetcode 108 | Approach + Code with explanation.
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

9 solutions   August 21, 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