#!/usr/bin/env python3 """ Implements a Binary Tree as a list, where each each node of the tree is given as a list: node = [ value, [left child], [right child]] """ __author__ = "Richard White" __version__ = "2019-04-10" def binary_tree(rootVal): """Creates a node with a root value and two empty lists as leaves. """ return [rootVal,[],[]] def get_root_val(root): return root[0] def set_root_val(root, newValue): """Sets the root value of the identified tree to a new value. """ root[0] = newValue def get_left_child(root): return root[1] def get_right_child(root): return root[2] def insert_left(root, new_branch): """Inserts a new branch at the left side of the root. If there is currently a tree there, that tree is moved down to become the left branch of the node inserted. """ tmp = get_left_child(root) root[1] = [new_branch, [], []] root[1][1] = tmp def insert_right(root, new_branch): """Inserts a new branch at the right side of the root. If there is currently a tree there, that tree is moved down to become the right branch of the node inserted. """ tmp = get_right_child(root) root[2] = [new_branch, [], []] root[2][2] = tmp def main(): t = binary_tree(3) print("Instruction: t = binary_tree(3)") print("Result:", t) print("Expect: [3, [], []]") insert_left(t, 4) print("Instruction: insert_left(t, 4)") print("Result:", t) print("Expect: [3, [4, [], []], []]") insert_left(t, 5) print("Instruction: insert_left(t, 5)") print("Result:", t) print("Expect: [3, [5, [4, [], []], []], []]") insert_right(t, 6) print("Instruction: insert_right(t, 6)") print("Result:", t) print("Expect: [3, [5, [4, [], []], []], [6, [], []]]") insert_right(t, 7) print("Instruction: insert_right(t, 7)") print("Result:", t) print("Expect: [3, [5, [4, [], []], []], [7, [], [6, [], []]]]") l = get_left_child(t) print("Instruction: l = get_left_child(t)") print("Result: l =", l) print("Expect: l = [5, [4, [], []], []]") set_root_val(l, 9) print("Instruction: set_root_val(l, 9)") print("Result: l =", l) print("Expect: l = [9, [4, [], []], []]") insert_left(l, 11) print("Instruction: insert_left(l, 11)") print("Result:", t) print("Expect: [3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]]") print("Instruction: print(get_right_child(get_right_child(t)))") print("Result:", get_right_child(get_right_child(t))) print("Expect: [6, [], []]") if __name__ == "__main__": main()