Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
根据前序遍历和中序遍历生成二叉树。
用递归方法很容易完成,先利用前序遍历找到根节点,然后再根据中序遍历分根节点的左子树和右子树。
需要注意的是和后序+中序有所不同,前序+中序要先写root.left,而前者要先写root.right。
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if inorder:
prenode=preorder.pop(0)
index = inorder.index(prenode)
root=TreeNode(inorder[index])
root.left=self.buildTree(preorder, inorder[:index])
root.right=self.buildTree(preorder, inorder[index+1:])
return root

本文介绍了一种使用前序遍历和中序遍历序列构建二叉树的方法。通过递归算法,首先确定根节点,然后划分左右子树,最终重构整个二叉树结构。
561

被折叠的 条评论
为什么被折叠?



