根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

  1. 3<br /> / \<br /> 9 20<br /> / \<br /> 15 7

解法一:递归

前序遍历的头元素为当前节点值,在中序中找到其左右子树的中序值,并在前序中通过左右子树的长度划分出左子树的前序及右子树的前序。

  1. class Solution:
  2. def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
  3. if not preorder or not inorder:
  4. return None
  5. root = TreeNode(preorder[0])
  6. idx = inorder.index(root.val)
  7. root.left = self.buildTree(preorder[1:idx+1], inorder[:idx])
  8. root.right = self.buildTree(preorder[idx+1:], inorder[idx+1:])
  9. return root

同类题目

106. 从中序与后序遍历序列构造二叉树

后续遍历的最末元素为当前节点值,在中序中找到其左右子树的中序值,并在后序中通过左右子树的长度划分出左子树的后序及右子树的后序。

  1. class Solution:
  2. def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
  3. if not inorder or not postorder:
  4. return None
  5. root = TreeNode(postorder[-1])
  6. i = inorder.index(root.val)
  7. root.left = self.buildTree(inorder[:i], postorder[:i])
  8. root.right = self.buildTree(inorder[i+1:], postorder[i:-1])
  9. return root