NeetCode #445LC-105MediumTreesBlind 75NC 150NC 250
← Back to All Problems#445 · #105 · Construct Binary Tree from Preorder and Inorder Traversal(从前序与中序遍历序列构造二叉树)
📌 Problem Statement & Constraints
Given two integer arrays
preorder and inorder representing the pre-order and in-order traversal of a binary tree, construct and return the tree. All values are distinct. Constraints: 1 <= preorder.length <= 3000, preorder.length == inorder.length.💡 Core Algorithmic Approaches
- The first element of the pre-order traversal is the root.
- In the in-order traversal, the root splits the array into the left and right subtrees; the size of the left part tells you how many nodes belong to the left subtree in the pre-order array.
- Precompute a value-to-index map for the in-order array so finding the split is O(1) instead of O(n).
- Recurse with the correct subarray bounds; the whole construction is O(n).
💻 Benchmark Python3 Implementation
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
idx = {v: i for i, v in enumerate(inorder)} # O(1) split lookup
def build(pl: int, pr: int, il: int, ir: int) -> Optional[TreeNode]:
if pl > pr:
return None
root = TreeNode(preorder[pl]) # pre-order's first is the root
m = idx[root.val] # split point in inorder
left_size = m - il
root.left = build(pl + 1, pl + left_size, il, m - 1)
root.right = build(pl + left_size + 1, pr, m + 1, ir)
return root
return build(0, len(preorder) - 1, 0, len(inorder) - 1)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is created once and each split lookup is O(1).
💾 Space Complexity
O(n) for the index map plus O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Slicing the arrays at each step: it works but allocates O(n log n) in total and hides the index arithmetic.
- Using
inorder.index(root.val): O(n) per node, giving O(n^2) overall. The precomputed map is essential. - Computing
left_sizefrom the wrong bounds: it ism - il, the number of in-order elements before the root. - Mixing up the pre-order subarray bounds: the left subtree occupies
pl + 1topl + left_size, and the right starts atpl + left_size + 1.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
从前序与中序遍历序列构造二叉树
给定两个整数数组 preorder 和 inorder,其中 preorder 是二叉树的 先序遍历 ,inorder 是同一棵树的 中序遍历 ,请构造二叉树并返回其根节点。约束:1 ≤ preorder.length ≤ 3000;inorder.length == preorder.length;-3000 ≤ preorder[i], inorder[i] ≤ 3000;preorder 和 inorder 均 无重复元素 ;preorder 均出现在 inorder;inorder 均出现在 preorder;preorder 保证为二叉树的前序遍历序列;inorder 保证为二叉树的中序遍历序列。
核心要点
- 递归划分(标准解) :前序的第一个元素是根;在中序中找到该元素的位置,它左侧是左子树、右侧是右子树;据此计算左右子树的元素个数,在前序中切分出对应的区间。
- 关键:用哈希表定位根在中序中的位置 :若每次都用 inorder.index() 查找是 O(n),整体退化为 O(n²)。预处理 值 → 中序下标 的映射可做到 O(1) 定位。
- 区间边界的推导 :设中序中根的下标为 k ,左子树大小 left_size = k − il 。则前序中左子树区间为 [pl+1, pl+left_size] ,右子树为 [pl+left_size+1, pr] 。
- 复杂度 :O(n) 时间、O(n) 空间(哈希表 + 递归栈)。
常见陷阱
- 用 inorder.index() 每次查找 :O(n) 每次,整体 O(n²) 会超时。必须预建哈希表。
- 左右子树的区间边界算错 : left_size = k − il ,前序左子树是 [pl+1, pl+left_size] 。写成 [pl+1, pl+k] 会错位。
- 递归终止条件写成 pl >= pr :会导致叶子节点无法创建。应为 pl > pr 。
- 误以为「前序 + 中序」与「后序 + 中序」写法相同 :后序的根在末尾,区间划分方式不同。
参考实现
class Solution:
def buildTree(self, preorder: list[int], inorder: list[int]) -> 'TreeNode':
idx = {v: i for i, v in enumerate(inorder)} # 值 -> 中序下标
def build(pl: int, pr: int, il: int, ir: int):
if pl > pr:
return None
root = TreeNode(preorder[pl]) # 前序第一个是根
k = idx[root.val] # 根在中序中的位置
left_size = k - il # 左子树节点数
root.left = build(pl + 1, pl + left_size, il, k - 1)
root.right = build(pl + left_size + 1, pr, k + 1, ir)
return root
return build(0, len(preorder) - 1, 0, len(inorder) - 1)