def rebuild1(inorder, postorder): if len(inorder) == 0: return None if len(inorder) == 1: return Node(inorder[0]) root = Node(postorder[-1]) p = inorder.index(postorder[-1]) root.left = rebuild1(inorder[:p], postorder[:p]) root.right = rebuild1(inorder[p+1:], postorder[p:-1]) return root
def rebuild2(preorder, inorder): if len(inorder) == 0: return None if len(inorder) == 1: return Node(inorder[0]) root = Node(preorder[0]) p = inorder.index(preorder[0]) root.left = rebuild2(preorder[1:p+1], inorder[:p]) root.right = rebuild2(preorder[p+1:], inorder[p+1:]) return root