题目标题

能否实现一个重建二叉树?

参考解析
  1. # class TreeNode:
  2. # def __init__(self, x):
  3. # self.val = x
  4. # self.left = None
  5. # self.right = None
  6. class Solution:
  7. def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
  8. if not preorder or not inorder:
  9. return
  10. root = TreeNode(preorder[0])
  11. index = inorder.index(preorder[0])
  12. root.left = self.buildTree(preorder[1:index+1], inorder[:index])
  13. root.right = self.buildTree(preorder[index+1:], inorder[index+1:])
  14. return root