本文完整拆解 LeetCode 105 Construct Binary Tree from Preorder 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Construct Binary Tree from Preorder 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
Example 2:
Input: preorder = [-1], inorder = [-1] Output: [-1]
Constraints:
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorderandinorderconsist of unique values.- Each value of
inorderalso appears inpreorder. preorderis guaranteed to be the preorder traversal of the tree.inorderis guaranteed to be the inorder traversal of the tree.
內容目錄
TogglePython
# time complexity: O(n)
# space complexity: O(n)
from typing import List, Optional
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
def dfs(left: int, right: int):
nonlocal preorderIndex
if left > right:
return None
rootValue = preorder[preorderIndex]
root = TreeNode(rootValue)
preorderIndex += 1
root.left = dfs(left, inorderMap[rootValue] - 1)
root.right = dfs(inorderMap[rootValue] + 1, right)
return root
preorderIndex = 0
inorderMap = {}
for i, value in enumerate(inorder):
inorderMap[value] = i
return dfs(0, len(inorder) - 1)
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
print(Solution().buildTree(preorder, inorder))
Construct Binary Tree from Preorder and Inorder Traversal 解題思路
前序走訪的第一個元素一定是根;在中序走訪中找到這個根,它左邊的就是左子樹、右邊的就是右子樹。遞迴地重複這個切分就能還原整棵樹。為了避免每次都線性搜尋中序陣列,先用雜湊表把「值 → 中序索引」建好,查找就變成 O(1)。
Construct Binary Tree from Preorder and Inorder Traversal 演算法步驟
- 建立雜湊表記錄中序陣列中每個值的索引。
- 用一個指標 preIdx 從 0 開始,依序消耗前序陣列。
- 定義 build(inLeft, inRight):區間為空時回傳 null;否則取 preorder[preIdx++] 當根。
- 用雜湊表查出根在中序中的位置 mid,先遞迴建左子樹 (inLeft, mid-1),再建右子樹 (mid+1, inRight)。
Construct Binary Tree from Preorder and Inorder Traversal 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n) |
| 空間複雜度 | O(n) |
每個節點只被建立一次,雜湊表查找 O(1),所以時間是 O(n)。雜湊表佔 O(n),遞迴堆疊最壞 O(n)(退化成鏈),整體空間 O(n)。
Construct Binary Tree from Preorder and Inorder Traversal 的邊界情況與常見錯誤
- 先建左子樹再建右子樹的順序不能顛倒,因為 preIdx 是共用的遞增指標。
- 樹中若有重複值,雜湊表會對應錯誤,本題假設值互異。
- 空陣列要回傳 null。
- 改用「前序 + 後序」無法唯一還原二元樹,只有搭配中序才可以。
Construct Binary Tree from Preorder and Inorder Traversal 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 每層線性搜尋中序找根 | O(n²) | O(n) | 退化成鏈時特別慢 |
| 迭代 + 堆疊還原 | O(n) | O(n) | 省去遞迴但邏輯較難 |
| 雜湊表索引 + 遞迴切分 | O(n) | O(n) | 本文採用 |
