Problem 106

Abstract / Summary

Given inorder and postorder sequences of a binary tree build the tree using those sequences.

Note

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

Python 0106.py

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        # almost the same as problem 105
        def parse(post, inn):
            if not inn:
                return None

            value = post[-1]
            node = TreeNode(value)
            if len(inn) == 1:
                return node

            pos = inn.index(value)

            inn_left  = inn[:pos]
            inn_right = inn[pos+1:]
            inn_left_faster = frozenset(inn_left)
            post_left  = []
            post_right = []
            for p in post[:-1]:
                if p in inn_left_faster:
                    post_left.append(p)
                else:
                    post_right.append(p)

            node.left  = parse(post_left,  inn_left)
            node.right = parse(post_right, inn_right)
            return node

        return parse(postorder, inorder)
30 lines | 944 bytes | submitted August 31, 2023 | GitHub   4% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (1+ 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 constructs a binary tree from its inorder and postorder traversals. It follows the classic divide-and-conquer strategy: the last element of the postorder list is the root, the inorder list is split around that root to obtain left and right sub-trees, and the process recurses on the corresponding slices of the two traversal lists. The code is wrapped in a Solution class with a public buildTree method that delegates the work to an inner helper parse.

Core Recursive Function

def parse(post, inn):
    if not inn:
        return None
    value = post[-1]
    node = TreeNode(value)
    if len(inn) == 1:
        return node
    pos = inn.index(value)
    inn_left  = inn[:pos]
    inn_right = inn[pos+1:]
    inn_left_faster = frozenset(inn_left)
    post_left  = []
    post_right = []
    for p in post[:-1]:
        if p in inn_left_faster:
            post_left.append(p)
        else:
            post_right.append(p)
    node.left  = parse(post_left,  inn_left)
    node.right = parse(post_right, inn_right)
    return node

The helper receives two lists: post (the current postorder slice) and inn (the current inorder slice). It returns a TreeNode representing the root of the subtree defined by those slices.

Base Cases

The first conditional checks whether the inorder slice is empty. An empty inorder list means there are no nodes to construct, so the function returns None. This handles the situation where a recursive call corresponds to a missing child.

The second conditional tests whether the inorder slice contains exactly one element. In that case the node created from the sole value is a leaf, and the function returns it directly without further recursion. This captures the leaf-node edge case efficiently.

Determining the Root

value = post[-1]
node = TreeNode(value)

The last element of the postorder slice is always the root of the current subtree. A new TreeNode is instantiated with that value.

Splitting the Inorder Slice

pos = inn.index(value)
inn_left  = inn[:pos]
inn_right = inn[pos+1:]

The position of the root value within the inorder slice is located using list.index. Elements to the left of that position belong to the left subtree, and elements to the right belong to the right subtree. This partition yields inn_left and inn_right.

Faster Membership Test for Postorder Partition

inn_left_faster = frozenset(inn_left)
post_left  = []
post_right = []
for p in post[:-1]:
    if p in inn_left_faster:
        post_left.append(p)
    else:
        post_right.append(p)

To separate the postorder slice into left-subtree and right-subtree portions, the code builds a frozenset from inn_left. Membership checks against a set are O(1) on average, which speeds up the classification of each element in post[:-1]. Elements found in the set are appended to post_left; all others go to post_right. This approach avoids repeated linear scans of the inorder list during the partitioning loop.

Recursive Construction

node.left  = parse(post_left,  inn_left)
node.right = parse(post_right, inn_right)

With the left and right slices prepared, the function recurses to build the left and right subtrees. The results are attached to the current node’s left and right attributes, respectively.

Entry Point

def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
    return parse(postorder, inorder)

The public method simply forwards the full traversal lists to the recursive helper, initiating the construction process.

Edge Cases Handled

The implementation gracefully handles an empty tree by returning None when the inorder list is empty. It also correctly processes a tree consisting of a single node, where the inorder and postorder lists each contain one element; the early return after the length-check prevents unnecessary recursion. Additionally, the use of frozenset ensures that even when the left subtree contains many nodes, membership checks remain efficient, preventing performance degradation on skewed trees.

Performance Optimizations

The most notable optimization is the conversion of the left inorder slice into a frozenset. This transforms repeated containment checks from O(k) per check (where k is the size of the left inorder slice) to O(1) average time, reducing the overall work required to partition the postorder slice. By constructing the set once per recursive call, the algorithm avoids the quadratic blow-up that would occur if it repeatedly called list.index or performed linear scans for each element.

Another subtle optimization is the early exit for leaf nodes (len(inn) == 1). By returning the node immediately, the function skips the overhead of building sets and iterating over the postorder slice when there is no further structure to process.

Overall, the code leverages set-based membership testing and early termination to keep the recursive construction efficient across a variety of tree shapes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine building a tower out of blocks, but we are doing it in reverse by looking at two different lists that tell us how the tower was arranged. The code works by looking at the very last piece mentioned in the postorder list, because that piece must be the one at the very top of the current tower section. Once that top piece is found, we look at the other list to see which pieces belong on the left side and which belong on the right side. The computer then takes those groups and repeats the same steps again, almost like solving a puzzle within a puzzle. It picks the next top piece for the left side and the next top piece for the right side, creating branches down the tree until every single block is back in its correct place. This keeps happening until everything is organized, making sure that every piece has its own spot connected to the rest of the tower.

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.42 | σ = 1.25

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 Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
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#
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, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
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#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
55 links | 40 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal | LeetCode 106 | C++, Java, Python3'
Knowledge Center 26 mins
Construct Binary Tree from Inorder and Postorder Traversal | LeetCode 106 | C++, Java, Python3
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal | Leetcode 106 | codestorywithMIK'
codestorywithMIK 26 mins
Construct Binary Tree from Inorder and Postorder Traversal | Leetcode 106 | codestorywithMIK
YouTube video 'Construct BinaryTree From PostOrder and InOrder Traversal | Leetcode 106 Solution'
Pepcoding 34 mins
Construct BinaryTree From PostOrder and InOrder Traversal | Leetcode 106 Solution
YouTube video 'construct binary tree from inorder and postorder traversal leetcode | leetcode 106 | binary tree'
Naresh Gupta 10 mins
construct binary tree from inorder and postorder traversal leetcode | leetcode 106 | binary tree
YouTube video '[Java] Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal [Binary Tree #7]'
Eric Programming 14 mins
[Java] Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal [Binary Tree #7]
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal | Leet code 106 | Theory + Python code'
Sai Anish Malla 15 mins
Construct Binary Tree from Inorder and Postorder Traversal | Leet code 106 | Theory + Python code
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal | Leetcode - 106'
Algorithms Made Easy 3 mins
Construct Binary Tree from Inorder and Postorder Traversal | Leetcode - 106
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal | Leetcode 106 | Live coding session πŸ”₯πŸ”₯πŸ”₯'
Coding Decoded 11 mins
Construct Binary Tree from Inorder and Postorder Traversal | Leetcode 106 | Live coding session πŸ”₯πŸ”₯πŸ”₯
YouTube video '106 || Construct Binary Tree from Inorder and Postorder Traversal || C++ || Leetcode Daily Challenge'
CodeFreaks 17 mins
106 || Construct Binary Tree from Inorder and Postorder Traversal || C++ || Leetcode Daily Challenge
YouTube video 'LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal'
Jeevan Kumar - Cracckify 8 mins
LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal | Leetcode 106'
Binod Suman Academy 22 mins
Construct Binary Tree from Inorder and Postorder Traversal | Leetcode 106
YouTube video '106. Construct Binary Tree from Inorder and Postorder Traversal | LeetCode daily | C++'
Priyanshi Porwal 18 mins
106. Construct Binary Tree from Inorder and Postorder Traversal | LeetCode daily | C++
YouTube video 'Daily Leetcode #118: Jul 27, 2020 - 106. Construct Binary Tree from Inorder and Postorder Traversal'
Programming Live with Larry 14 mins
Daily Leetcode #118: Jul 27, 2020 - 106. Construct Binary Tree from Inorder and Postorder Traversal
YouTube video 'LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal'
Kacy Codes 13 mins
LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
YouTube video 'LeetCode 106 - Construct Binary Tree from Inorder and Postorder Traversal [Daily Challenge]'
Code with Carter 23 mins
LeetCode 106 - Construct Binary Tree from Inorder and Postorder Traversal [Daily Challenge]
YouTube video 'LeetCode 106. Construct Binary Tree from Postorder and Inorder Traversal | Medium |Algorithm Explain'
Cherry Coding [IIT-G] 14 mins
LeetCode 106. Construct Binary Tree from Postorder and Inorder Traversal | Medium |Algorithm Explain
YouTube video 'Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal || Recursion || JAVA'
ExpertFunda 38 mins
Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal || Recursion || JAVA
YouTube video 'Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python'
Lit Code 10 mins
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
YouTube video 'leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal - recursion'
Code-Yao 7 mins
leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal - recursion
YouTube video 'LeetCode 106 | Construct Binary Tree from Inorder and Postorder Traversal | Divide & Conquer | Java'
Sleepy Cracker 7 mins
LeetCode 106 | Construct Binary Tree from Inorder and Postorder Traversal | Divide & Conquer | 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