def setUp(self): tree = Node(5) tree.left = Node(3) tree.left.right = Node(5) tree.left.left = Node(2) tree.right = Node(7) tree.right.right = Node(8) self.tree = tree
def insert(self, new_node: Any, current: Node, parent: Node = None) -> None: if self.root is None: self.root = new_node return parent = current if current.key < new_node.key: current = current.right else: current = current.left if current: # recursive self.insert(new_node, current, parent) else: if parent.key < new_node.key: parent.right = new_node else: parent.left = new_node
from binary_search_tree import Node def level_order_traversal(queue, result): if queue: node = queue.pop(0) if node is not None: if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) result.append(node) result = level_order_traversal(queue, result) return result if __name__ == '__main__': root = Node('A') queue = [root] root.left = Node('B') root.left.left = Node('D') root.left.right = Node('E') root.left.left.left = Node('G') root.left.right.right = Node('H') root.right = Node('C') root.right.right = Node('F') root.right.right.left = Node('I') print('Level-Order Traversal', level_order_traversal([root], []))
def create_level_linked_list(root, lists, level): if (root == None): return if (len(lists) == level): ## if the level has not been reached list = LL_Node(root.item) lists.append(list) else: list = lists[level] new = LL_Node(root.item) new.next = list list = new lists[level] = list create_level_linked_list(root.left, lists, level + 1) create_level_linked_list(root.right, lists, level + 1) def create_linked_list(root): lists = [] create_level_linked_list(root, lists, 0) return lists tree = Node(1, None, None) tree.left = Node(2, None, None) tree.right = Node(3, None, None) r = create_linked_list(tree) print(r[1].next)
left = None if left and right: if right < left: # print("Left greater than right") raise Exception else: return True is_valid(root.right) is_valid(root.left) if __name__ == "__main__": tree = Tree() tree.insert(1) tree.insert(2) tree.insert(10) tree.insert(6) try: is_valid(tree.root) except: print("Tree is invalid") invalid_root = Node(2) right = Node(4) left = Node(5) invalid_root.right = right invalid_root.left = left try: is_valid(invalid_root) except: print("The invalid tree was classified as is invalid")