def all_paths_root_to_leaves_v1(root): if root == None: return all_paths_root_to_leaves_v1.paths.append(root.key) all_paths_root_to_leaves_v1(root.left) if is_leaf(root): print(all_paths_root_to_leaves_v1.paths) all_paths_root_to_leaves_v1(root.right) all_paths_root_to_leaves_v1.paths.pop()
def is_bst_v2(root): if root is None or is_leaf(root): return True left = root.left.key if root.left is not None else MIN right = root.right.key if root.right is not None else MAX return ((root.key >= left and root.key < right) and is_bst_v2(root.left) and is_bst_v2(root.right))
def is_sum_equal(root, total, sum=0): if root is None: return False sum += root.key if is_leaf(root) and total == sum: return True return is_sum_equal(root.left, total, sum) or is_sum_equal( root.right, total, sum)
def all_paths_root_to_leaves_v3(root, path = []): if root is None: return path.append(root.key) if is_leaf(root): for elt in path: print(elt, end=',') print('\n') else: all_paths_root_to_leaves_v3(root.left, deepcopy(path)) all_paths_root_to_leaves_v3(root.right, deepcopy(path))
def all_paths_with_sum(root, total, path, path_len=0): if root == None: return path[path_len] = root.key path_len += 1 if is_leaf(root) and sum(path[0:path_len]) == total: all_paths_with_sum.paths_with_sum.append(path[0:path_len]) else: all_paths_with_sum(root.left, total, path, path_len=path_len) all_paths_with_sum(root.right, total, path, path_len=path_len)
def is_bst_v2(root): if root is None or is_leaf(root): return True left = root.left.key if root.left is not None else MIN right = root.right.key if root.right is not None else MAX return ( (root.key >= left and root.key < right) and is_bst_v2(root.left) and is_bst_v2(root.right) )
def children_sum(root): if root is None: return False if is_leaf(root): return True lkey = root.left.key if root.left is not None else 0 rkey = root.right.key if root.right is not None else 0 if root.key != (lkey + rkey): return False return children_sum(root.left) and children_sum(root.right)
def all_paths_root_to_leaves_v2(root, path, path_len): if root == None: return path[path_len] = root.key path_len += 1 if is_leaf(root): for i in range(0, path_len): print(path[i], end=',') print('\n') else: all_paths_root_to_leaves_v2(root.left, path, path_len) all_paths_root_to_leaves_v2(root.right, path, path_len)
def move_children_left_v3(root): if is_leaf(root): return if root.right is not None: ltemp = root.left root.left = root.right root.right = None lmost = root.left while lmost.left is not None: lmost = lmost.left lmost.left = ltemp move_children_left_v2(root.left)