105. Construct Binary Tree from Preorder and Inorder Traversal
My accepted Python solution to LeetCode problem 105, Construct Binary Tree from Preorder and Inorder Traversal, running in 7ms.
- Difficulty: Medium
- Python
- Runtime 7ms
- Memory 17MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 7ms, memory 17MB, accepted 2025-12-24.
class Solution:
def buildTree(self, preorder, inorder):
if not preorder or not inorder:
return None
inorder_map = {val: idx for idx, val in enumerate(inorder)}
self.pre_idx = 0
def build(left, right):
if left > right:
return None
root_val = preorder[self.pre_idx]
self.pre_idx += 1
root = TreeNode(root_val)
mid = inorder_map[root_val]
root.left = build(left, mid - 1)
root.right = build(mid + 1, right)
return root
return build(0, len(inorder) - 1)