105. Construct Binary Tree from Preorder and Inorder Traversal
题目
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.
Related Topics
思路
dfs 通过遍历 tree
- 通过 hashmap 存储 inorder 值的位置,将查找复杂度由 O(N) -> O(1)
- 递归时 通过记录 索引,而不是拆分数组,可降低空间消耗
- 函数内使用到外部的变量时需要手动声明
- nolocal 声明变量
解法
py
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
in_dict = {
pre_index = 0
for i in range(len(inorder)):
in_dict[inorder[i]] = i
def buildSubTree(in_left, in_right) -> Optional[TreeNode]:
nonlocal pre_index
if in_left > in_right:
return None
root = TreeNode(preorder[pre_index])
pre_index += 1
root_index = in_dict[root.val]
root.left = buildSubTree(in_left, root_index - 1)
root.right = buildSubTree(root_index + 1, in_right)
return root
return buildSubTree(0, len(inorder) - 1)
# leetcode submit region end(Prohibit modification and deletion)复杂度分析
- 时间复杂度 O(N)
- 空间复杂度 O(N)