def case05(): print("\nA base case:\n") n0 = BinaryNode(item="Ziang") n1 = BinaryNode(item="Adam") n2 = BinaryNode(item="Barry", lchild=n0, rchild=n1) bt = BinaryTree(root=n2) print("Balanced = {}.".format(bt.is_balanced())) bt.pretty_print()
def case01(): print("\nA balanced tree (in fact, perfectly balanced):\n") n1 = BinaryNode(item="Adam") n2 = BinaryNode(item="Barry") n3 = BinaryNode(item="Charles") n4 = BinaryNode(item="Daniel") n5 = BinaryNode(item="Edward", lchild=n1, rchild=n2) n6 = BinaryNode(item="Frank", lchild=n3, rchild=n4) n7 = BinaryNode(item="Greg", lchild=n5, rchild=n6) bt = BinaryTree(root=n7) print("Balanced = {}.".format(bt.is_balanced())) bt.pretty_print()
def case04(): print("\nAn unbalanced tree (but not perfectly unbalanced):\n") n00 = BinaryNode(item="Yang") n0 = BinaryNode(item="Ziang", lchild=n00) n1 = BinaryNode(item="Adam", rchild=n0) n2 = BinaryNode(item="Barry") n3 = BinaryNode(item="Charles") n4 = BinaryNode(item="Daniel") n5 = BinaryNode(item="Edward", lchild=n1, rchild=n2) n6 = BinaryNode(item="Frank", lchild=n3, rchild=n4) n7 = BinaryNode(item="Greg", lchild=n5, rchild=n6) bt = BinaryTree(root=n7) print("Balanced = {}.".format(bt.is_balanced())) bt.pretty_print()
def case06(): print("\nAn even simpler base case:\n") n0 = BinaryNode(item="Jeff") bt = BinaryTree(root=n0) print("Balanced = {}.".format(bt.is_balanced())) bt.pretty_print()
if __name__ == "__main__": bt = BinaryTree() bt.root = BinaryNode(item=1) bt.root.lchild = BinaryNode(item=2, parent=bt.root) bt.root.rchild = BinaryNode(item=3, parent=bt.root) bt.root.lchild.lchild = BinaryNode(item=4, parent=bt.root.lchild) bt.root.lchild.rchild = BinaryNode(item=5, parent=bt.root.lchild) bt.root.rchild.lchild = BinaryNode(item=6, parent=bt.root.rchild) bt.root.rchild.rchild = BinaryNode(item=7, parent=bt.root.rchild) # For now assume bt.root itself is not None. print("\nHere's the tree, and inorder/preorder/postorder traversals ...") bt.pretty_print() inorder(bt.root) print(" (Inorder)") preorder(bt.root) print(" (Preorder)") postorder(bt.root) print(" (Postorder)") print("\nNow testing question 6...") print("root successor {}".format(bt.root)) print(inorder_successor(bt.root)) print("root.lchild successor {}".format(bt.root.lchild)) print(inorder_successor(bt.root.lchild)) print("root.rchild successor {}".format(bt.root.rchild)) print(inorder_successor(bt.root.rchild))