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)
Difficulty
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
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 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.
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.
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 | 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++ |
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 106: Construct Binary Tree from Inorder and Postorder 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