给出一棵树的前序遍历和中序遍历,请构造这颗二叉树
注意:
可以假设树中不存在重复的节点
class Solution: def buildTree(self , preorder , inorder ): # write code here node = None if preorder: node = TreeNode(preorder[0]) index = inorder.index(preorder[0]) node.left = self.buildTree(preorder[1:1 + index], inorder[:index]) node.right = self.buildTree(preorder[index + 1:], inorder[index + 1:]) return node
class Solution: def buildTree(self , preorder , inorder ): # write code here if not inorder&nbs***bsp;not preorder: return None root = TreeNode(preorder.pop(0)) index = inorder.index(root.val) root.left = self.buildTree(preorder, inorder[:index]) root.right = self.buildTree(preorder, inorder[index+1:]) return root