lintcode_73. 前序遍历和中序遍历树构造二叉树
---恢复内容开始---
根据前序遍历和中序遍历树构造二叉树.
注意事项
你可以假设树中不存在相同数值的节点
样例
给出中序遍历:[1,2,3]
和前序遍历:[2,1,3]
. 返回如下的树:
2 / \ 1 3
思路:前序遍历的第一个节点为根节点,在中序遍历中,其左边点数为根节点的左节点,右为右节点
class Solution: """ @param preorder : A list of integers that preorder traversal of a tree @param inorder : A list of integers that inorder traversal of a tree @return : Root of a tree """ def buildTree(self, preorder, inorder): # write your code here if len(preorder) > 0: root = TreeNode(preorder[0]) else: return index_root = inorder.index(preorder[0]) #找到根节点在中序遍历中的位置,一分为二 root.left = self.buildTree(preorder[1:index_root+1],inorder[:index_root]) root.right = self.buildTree(preorder[index_root+1:],inorder[index_root+1:]) return root
---恢复内容结束---