temp.extend(left) temp.extend(right) weaved.append(temp) return # both left and right are not empty # recurse with head of the first list added to the prefix. # remove the head will damage the first, so we'll need to put it back where we found it afterwards head = left.pop(0) prefix.append(head) weave_lists(left, right, weaved, prefix) prefix.pop() left.insert(0, head) # do same thing with second, damaging then restoring the list head = right.pop(0) prefix.append(head) weave_lists(left, right, weaved, prefix) prefix.pop() right.insert(0, head) if __name__ == '__main__': bst = BinarySearchTree(2) bst.insert(1) bst.insert(3) root = bst.get_root() print bst_sequences(root) # weaved = [] # weave_lists([1,2], [3,4], weaved, []) # print weaved
def check_balanced_recur(node, count, min_max): # pre order traversal if node is None: return if node.left is None and node.right is None: if count < min_max[0]: min_max[0] = count if count > min_max[1]: min_max[1] = count check_balanced_recur(node.left, count + 1, min_max) check_balanced_recur(node.right, count + 1, min_max) if __name__ == '__main__': bst1 = BinarySearchTree(27) bst1.insert(9) bst1.insert(3) bst1.insert(1) bst1.insert(53) root1 = bst1.get_root() print check_balanced(root1) # false bst2 = BinarySearchTree(27) bst2.insert(9) bst2.insert(3) bst2.insert(1) bst2.insert(53) bst2.insert(30) root2 = bst2.get_root() print check_balanced(root2) # True
bstree.insert_element(8) bstree.insert_element(9) bstree.insert_element(4) bstree.insert_element(12) bstree.insert_element(17) bstree.insert_element(21) bstree.insert_element(52) print("\n") for p in bstree: print(p, end=" ") print("\n") arg = 12 result = bstree.binary_search(arg, bstree.get_root()) if result is None: print("Element {} is not found in container".format(arg)) else: print("Element {} is found in container".format(arg)) print("\nBreath first") for p in bstree.breadth_first(): print(p.get_element(), end=" ") print("\nDepth first") for p in bstree.depth_first(): print(p.get_element(), end=" ")