Problem 105

Abstract / Summary

Given preorder and inorder lists of a binary tree build the tree using their node order information.

Note

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

Python 0105.py

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        def parse(pree, inn):
            if not inn:
                return None

            value = pree[0]
            node = TreeNode(value)
            if len(inn) == 1:
                return node

            pos = inn.index(value)

            inn_left  = inn[:pos]
            inn_right = inn[pos+1:]
            pree_left  = []
            pree_right = []

            inn_left_faster = set(inn_left)
            for p in pree[1:]:
                if p in inn_left_faster:
                    pree_left.append(p)
                else:
                    pree_right.append(p)

            node.left  = parse(pree_left,  inn_left)
            node.right = parse(pree_right, inn_right)
            return node

        return parse(preorder, inorder)
30 lines | 894 bytes | submitted August 31, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Binary Tree
  • Divide And Conquer
  • Hash Table
  • 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 reconstructs a binary tree from its preorder and inorder traversal sequences. The Solution class exposes a single public method buildTree that receives two lists of integers and returns the root of the reconstructed tree, or None when the input is empty. The core of the algorithm resides in the nested helper function parse, which recursively partitions the traversal lists into left-subtree and right-subtree segments and creates TreeNode objects accordingly.

Core Logic

The recursion begins by checking whether the inorder segment is empty. An empty inorder list signifies that there is no subtree to construct, and the function returns None. This base case also covers the situation where the original input lists are empty, resulting in an immediate None return from buildTree.

if not inn:
    return None

When the inorder segment contains elements, the first element of the preorder segment is taken as the root value. A new TreeNode is instantiated with this value.

value = pree[0]
node = TreeNode(value)

If the inorder segment consists of a single element, the node is a leaf. The function returns the node without further recursion.

if len(inn) == 1:
    return node

The position of the root value within the inorder list determines the boundary between left and right subtrees. The code uses list.index to locate this position.

pos = inn.index(value)

Slices of the inorder list are then created to represent the left and right inorder partitions.

inn_left  = inn[:pos]
inn_right = inn[pos+1:]

Two empty lists, pree_left and pree_right, are prepared to hold the preorder elements that belong to the left and right subtrees respectively.

pree_left  = []
pree_right = []

Edge Cases Handled

The algorithm explicitly handles the case where the inorder segment has length one, treating the node as a leaf and avoiding unnecessary further slicing or set construction. It also gracefully handles empty input lists through the initial if not inn guard, ensuring that a None tree is returned without raising an exception.

When the preorder list contains elements that are not present in the left inorder slice, they are automatically placed into the right preorder slice. This logic correctly deals with trees that are heavily skewed to one side, such as completely left-leaning or right-leaning trees, because the set membership test directs each preorder element to the appropriate side based on the current inorder partition.

Partitioning Preorder Elements

To separate preorder elements into left and right groups, the code first builds a set from the left inorder slice. This set enables O(1) membership checks for each remaining preorder element.

inn_left_faster = set(inn_left)
for p in pree[1:]:
    if p in inn_left_faster:
        pree_left.append(p)
    else:
        pree_right.append(p)

Using a set rather than repeated linear searches on the list reduces the cost of the partitioning step, especially when the subtree contains many nodes. The loop iterates over the preorder list starting from the second element (the first element is the root) and distributes each value based on its presence in the left inorder set.

Recursive Construction

After the preorder lists have been divided, the function recursively builds the left and right subtrees by invoking parse with the corresponding preorder and inorder slices.

node.left  = parse(pree_left,  inn_left)
node.right = parse(pree_right, inn_right)

The recursion proceeds until it reaches the base cases described earlier, at which point the fully linked tree is assembled and the root node is returned to the caller.

Performance Optimizations

The most notable optimization is the conversion of the left inorder slice into a set for fast membership testing. This avoids repeated linear scans of the left inorder list for each preorder element, which would otherwise lead to quadratic behavior in the worst case. By performing a single set construction per recursive call, the algorithm achieves a more favorable runtime profile while still using only standard Python data structures.

Another subtle optimization is the early return when the inorder slice length is one. By detecting leaf nodes early, the algorithm skips the overhead of set creation and the partitioning loop for those cases, reducing unnecessary work for large numbers of leaf nodes.

Summary of Execution Flow

The buildTree method delegates all work to the nested parse function. parse checks for an empty inorder segment, creates a root node from the first preorder element, identifies the root's position in the inorder list, slices the inorder list into left and right parts, builds a set from the left inorder slice, partitions the remaining preorder elements into left and right lists using the set, recursively constructs left and right subtrees, attaches them to the root node, and finally returns the constructed node. This process repeats until the entire tree is reconstructed, and the root node is returned to the original caller.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you are building a magical tree where every piece of information has a specific spot. This code starts with two lists that act like a map for where each branch and number should go. First, it looks at the very front of the map to find the root, which is the main trunk of the tree. Once the trunk is placed, the code searches through the other list to see which numbers belong on the left side and which ones belong on the right side.

After it figures out the split, it builds a little branch for the left side and a little branch for the right side. Then, it does the exact same thing again for those smaller parts. It keeps going deeper and deeper, repeating the steps until every single number is tucked into its own place within the tree structure. It is just like putting together a puzzle where you follow the clues to make sure every shape fits exactly where it belongs.

written by google gemini

Code Quality

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

Complexity Analysis

Time: polynomial
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 TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca 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++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
60 links | 44 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Construct Binary Tree From Preorder And Inorder Traversal | Leetcode 105 | codestorywithMIK'
codestorywithMIK 25 mins
Construct Binary Tree From Preorder And Inorder Traversal | Leetcode 105 | codestorywithMIK
YouTube video 'Create Binary Tree from pre-order and in-order traversal (LeetCode 105) | Easiest explanation'
Nikhil Lohia 14 mins
Create Binary Tree from pre-order and in-order traversal (LeetCode 105) | Easiest explanation
YouTube video 'Construct Binary Tree from Preorder and Postorder Traversal - Leetcode 889 - Python'
NeetCodeIO 23 mins
Construct Binary Tree from Preorder and Postorder Traversal - Leetcode 889 - Python
YouTube video 'Construct Binary Tree from Preorder and Postorder Traversal | Leetcode 889'
Techdose 12 mins
Construct Binary Tree from Preorder and Postorder Traversal | Leetcode 889
YouTube video 'construct binary tree from preorder and inorder traversal leetcode | leetcode 105 | binary tree'
Naresh Gupta 9 mins
construct binary tree from preorder and inorder traversal leetcode | leetcode 105 | binary tree
YouTube video '[Java] Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal [Binary Tree #5]'
Eric Programming 13 mins
[Java] Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal [Binary Tree #5]
YouTube video 'LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal | Blind 75'
Code In Motion 17 mins
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal | Blind 75
YouTube video 'Construct Binary Tree from Preorder and Inorder Traversal | LeetCode 105 | Theory + Python'
Sai Anish Malla 20 mins
Construct Binary Tree from Preorder and Inorder Traversal | LeetCode 105 | Theory + Python
YouTube video 'Construct Binary Tree from Preorder and Inorder Traversal | Leetcode 105 | Live coding session'
Coding Decoded 9 mins
Construct Binary Tree from Preorder and Inorder Traversal | Leetcode 105 | Live coding session
YouTube video 'Daily Leetcode #835: Jul 14, 2022 - 105. Construct Binary Tree from Preorder and Inorder Traversal'
Programming Live with Larry 8 mins
Daily Leetcode #835: Jul 14, 2022 - 105. Construct Binary Tree from Preorder and Inorder Traversal
YouTube video 'LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal | Medium | Algorithm Explain'
Cherry Coding [IIT-G] 13 mins
LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal | Medium | Algorithm Explain
YouTube video 'LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal'
Happy Coding 11 mins
LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
YouTube video 'Daily Leetcode #434: Jun 08, 2021 - 105. Construct Binary Tree from Preorder and Inorder Traversal'
Programming Live with Larry 18 mins
Daily Leetcode #434: Jun 08, 2021 - 105. Construct Binary Tree from Preorder and Inorder Traversal
YouTube video 'Construct Binary Tree from Preorder and Inorder Traversal | Leetcode 105 | Coders Camp'
Coders Camp 13 mins
Construct Binary Tree from Preorder and Inorder Traversal | Leetcode 105 | Coders Camp
YouTube video 'Construct Binary Tree from Preorder and Inorder Traversal - LeetCode #105 - C++'
Sean Chuah 16 mins
Construct Binary Tree from Preorder and Inorder Traversal - LeetCode #105 - C++
YouTube video 'Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal'
Algorithms Casts 15 mins
Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
YouTube video 'Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal [ JAVASCRIPT ].'
Web Fusion with Bharadwaj 15 mins
Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal [ JAVASCRIPT ].
YouTube video '57. Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal : Javascript'
Web Fusion with Bharadwaj 24 mins
57. Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal : Javascript
YouTube video 'Construct Binary Tree from Preorder and Inorder Traversal - LeetCode 105 - Python'
Alpha-Code 25 mins
Construct Binary Tree from Preorder and Inorder Traversal - LeetCode 105 - Python
YouTube video '105. Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal : JAVA'
Web Fusion with Bharadwaj 20 mins
105. Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal : JAVA
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

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