思路:先序遍历首位为根,然后基于根在中序遍历中拆分左、右子树,依次递归构建
注意:
1、root:1
2、idx:vin[root.val]
3、len(left) = [:idx]
4、len(right) = [idx+1:]
class Solution:
def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode:
if len(pre) == 0 and len(vin) == 0:
return
root = TreeNode(pre[0])
idx = vin.index(root.val)
left = self.reConstructBinaryTree(pre[1:1+idx], vin[:idx])
right = self.reConstructBinaryTree(pre[1+idx:], vin[idx+1:])
root.left = left
root.right = right
return root