根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3<br /> / \<br /> 9 20<br /> / \<br /> 15 7
解法一:递归
前序遍历的头元素为当前节点值,在中序中找到其左右子树的中序值,并在前序中通过左右子树的长度划分出左子树的前序及右子树的前序。
class Solution:def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:if not preorder or not inorder:return Noneroot = TreeNode(preorder[0])idx = inorder.index(root.val)root.left = self.buildTree(preorder[1:idx+1], inorder[:idx])root.right = self.buildTree(preorder[idx+1:], inorder[idx+1:])return root
同类题目
106. 从中序与后序遍历序列构造二叉树
后续遍历的最末元素为当前节点值,在中序中找到其左右子树的中序值,并在后序中通过左右子树的长度划分出左子树的后序及右子树的后序。
class Solution:def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:if not inorder or not postorder:return Noneroot = TreeNode(postorder[-1])i = inorder.index(root.val)root.left = self.buildTree(inorder[:i], postorder[:i])root.right = self.buildTree(inorder[i+1:], postorder[i:-1])return root
