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)
Difficulty
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
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 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.
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.
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 | 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++ |
Videos
Similar Problems
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 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- 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