# Binary trees using lists def binary_tree(r): return [r, [], []] def insert_left(root, new_branch): t = root.pop(1) if len(t) > 0: root.insert(1, [new_branch, t, []]) else: root.insert(1, [new_branch, [], []]) return root def insert_right(root, new_branch): t = root.pop(2) if len(t) > 0: root.insert(2, [new_branch, [], t]) else: root.insert(2, [new_branch, [], []]) return root def get_root_val(root): return root[0] def set_root_val(root, new_val): root[0] = new_val def get_left_child(root): return root[1] def get_right_child(root): return root[2] # MINE class BinaryTree: """A binary tree class with nodes as lists.""" DATA = 0 # just some constants for readability LEFT = 1 RIGHT = 2 def __init__(self, root_value, left=None, right=None): """Create a new BinaryTree with a given root value. root_value -- the value for the root node left -- the left subtree right -- the right subtree """ self.node = [root_value, left, right] def insert_left(self, value): """Inserts value to the left of this node. Pushes any existing left subtree down as the left child of the new node. """ self.node[self.LEFT] = BinaryTree(value, self.node[self.LEFT], None) def insert_right(self, value): """Inserts value to the right of this node. Pushes any existing left subtree down as the left child of the new node. """ self.node[self.RIGHT] = BinaryTree(value, None, self.node[self.RIGHT]) def set_value(self, new_value): """Sets the value of the node.""" self.node[self.DATA] = new_value def get_value(self): """Gets the value of the node.""" return self.node[self.DATA] def get_left_subtree(self): """Gets the left subtree of the node.""" return self.node[self.LEFT] def get_right_subtree(self): """Gets the right subtree of the node.""" return self.node[self.RIGHT] def __str__(self): return '['+str(self.node[self.DATA])+', '+str(self.node[self.LEFT])+', '+\ str(self.node[self.RIGHT])+']' r = binary_tree(3) insert_left(r, 4) insert_left(r, 5) insert_right(r, 6) insert_right(r, 7) l = get_left_child(r) print(l) set_root_val(l, 9) print(r) insert_left(l, 11) print(r) print() r = BinaryTree(3) r.insert_left(4) r.insert_left(5) r.insert_right(6) r.insert_right(7) l = r.get_left_subtree() print(l) l.set_value(9) print(r) l.insert_left(11) print(r) print() r = BinaryTree(1) r.insert_left(2) r.insert_right(3) r.insert_right(4) r.get_left_subtree().insert_left(5) r.get_left_subtree().insert_right(6) print(r) print(r.get_left_subtree()) print(r.get_right_subtree()) print(r.get_left_subtree().get_left_subtree())