从前序与中序遍历序列构造二叉树
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
只需注意对边界的把控
class Solution:def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:inorderDict={}for i in range(len(inorder)):inorderDict[inorder[i]] = idef helper(preL:int,preR:int,inL:int,inR:int)->Optional[TreeNode]:if preL>=preR:return Nonemid=preorder[preL]midIndex = inorderDict[mid]return TreeNode(mid,helper(preL+1,preL+midIndex-inL+1,inL,midIndex), helper(preL+midIndex-inL+1,preR,midIndex+1,inR))return helper(0,len(preorder),0,len(preorder))