def constructtree(self, preorder, inorder, k1, Lk1, k2, Lk2): rootval = preorder[k1] root = BinaryTreeNode(rootval) if k1 == Lk1: if k2 == Lk2 and preorder[k1] == inorder[k2]: return root else: raise ValueError rootino = k2 while rootino <= Lk2 and inorder[rootino] != rootval: rootino += 1 if rootino == Lk2 and inorder[rootino] != rootval: raise ValueError leftlength = rootino - k2 leftpreo = k1 + leftlength if leftlength > 0: root.left_ = self.constructtree(preorder, inorder, k1 + 1, leftpreo, k2, rootino - 1) if leftlength < (Lk1 - k1): root.right_ = self.constructtree(preorder, inorder, leftpreo + 1, Lk1, rootino + 1, Lk2) return root
def deserializetree(self, ls): if len(ls) <= 0: return None val = ls.pop(0) root = None if val != '$': root = BinaryTreeNode(int(val)) root.left_ = self.deserializetree(ls) root.right_ = self.deserializetree(ls) return root