算法编程 dfs 从先序和中序遍历还原二叉树
105. 从前序与中序遍历序列构造二叉树
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1] 输出: [-1]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
和inorder
均 无重复 元素inorder
均出现在preorder
preorder
保证 为二叉树的前序遍历序列inorder
保证 为二叉树的中序遍历序列
# 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]: inorder_map = {val:i for i,val in enumerate(inorder)} n = len(preorder) nth = 0 def dfs(start, end): nonlocal nth if start > end: return None val = preorder[nth] i = inorder_map[val] root = TreeNode(val) if start <= i-1: nth += 1 root.left = dfs(start, i-1) if i+1 <= end: nth += 1 root.right = dfs(i+1, end) return root return dfs(0, n-1)