def main(): tree = BST() N = 11 _set = set([random.randint(1, N * N) for _ in range(N)]) for x in _set: tree.insert(x, "") print "original tree" tree.pretty_print() inorder = [node.key for node in tree.inorder_nodes()] preorder = [node.key for node in tree.preorder_nodes()] # now build a new tree from these traversals root = binary_tree_from_traversals(preorder, inorder) new_tree = BST() new_tree.root = root print "reconstructed tree" new_tree.pretty_print() # verify the correctness for orig_node, cloned_node in zip(tree.levelorder_nodes(), new_tree.levelorder_nodes()): assert orig_node is not cloned_node assert orig_node.key == cloned_node.key
def main(): complete_binary_tree = BST() one = Node(1) two = Node(2) three = Node(3) four = Node(4) five = Node(5) six = Node(6) seven = Node(7) one.left = two one.right = three two.left = four two.right = five three.left = six three.right = seven complete_binary_tree.root = one add_sibling_pointers(complete_binary_tree.root) nodes = list(complete_binary_tree.levelorder_nodes()) # verify the next pointers assert one.next is None assert two.next is three assert three.next is None assert four.next is five assert five.next is six assert six.next is seven assert seven.next is None
def main(): one = Node(1, "") two = Node(2, "") three = Node(3, "") four = Node(4, "") five = Node(5, "") six = Node(6, "") seven = Node(7, "") eight = Node(8, "") nine = Node(9, "") one.left = two one.right = three two.left = four two.right = five four.left = six four.right = seven tree = Tree() tree.root = one tree.levelorder() inverted = upside_down(tree) inverted.levelorder()
def upside_down(tree): d = {} traverse_left(tree.root, None, d) inverted = Tree() inverted.root = d['root'] return inverted
def main(): N = 22 arr = sorted([random.randint(1, N * N) for _ in range(N)]) print arr root = balanced_bst_from_sorted_array(arr, 0, len(arr) - 1) tree = BST() tree.root = root tree.pretty_print() inorder = [node.key for node in tree.inorder_nodes()] assert arr == inorder
def merge(t1, t2): inorder_t1 = [] inorder_t2 = [] inorder(t1.root, inorder_t1) inorder(t2.root, inorder_t2) merged_arr = sorted(inorder_t1 + inorder_t2) print_nodes(merged_arr) root = balanced_bst_from_sorted_array(merged_arr, 0, len(merged_arr) - 1) tree = BST() tree.root = root return tree
def main(): tree = BST() N = 10 _set = set([random.randint(1, N * N) for _ in range(N)]) for x in _set: tree.insert(x, "") new_root = clone(tree.root) new_tree = BST() new_tree.root = new_root for orig_node, cloned_node in zip(tree.levelorder_nodes(), new_tree.levelorder_nodes()): assert orig_node is not cloned_node assert orig_node.key == cloned_node.key assert orig_node.data == cloned_node.data