class BTNode:def __init__(self, val):self.left = Noneself.right = Noneself.val = val'''@ construct tree by inorder & preorder'''def constructByInPre(inorder, instart, inend, preorder, prestart, preend):if inend < instart or preend < prestart:return Noneif len(preorder) != len( inorder ) :return None# preorder visit: root, left, rightfor i in range(instart, inend + 1):if inorder[i] == preorder[prestart]: breakif i > inend:print "wrong data"return Noneroot = BTNode(inorder[i])root.left = constructByInPre(inorder, instart, i - 1, preorder, prestart + 1, preend)root.right = constructByInPre(inorder, i + 1, inend, preorder, prestart + 2, preend)return root'''@ construct tree by inorder & postorder'''def constructByInPost(inorder, instart, inend, postorder, posstart, posend):if inend < instart or posend < posstart:return Noneif len(postorder) != len(inorder):return None# posterorder visit: left, right, rootfor i in range(instart, inend + 1):if inorder[i] == postorder[posend]: breakif i > inend:print "wrong data"return Noneroot = BTNode(inorder[i])leftlen = i - instartroot.left = constructByInPost(inorder, instart, i - 1, postorder, posstart, posstart + leftlen - 1)root.right = constructByInPost(inorder, i + 1, inend, postorder, posstart + leftlen, posend - 1)return root