Exemple #1
0
        return 0

    paths = 0
    curr += root.val
    if curr == target_value:
        paths = 1
    diff = curr - target_value
    if diff in running_sum:
        paths += running_sum[diff]

    if curr in running_sum:
        running_sum[curr] += 1
    else:
        running_sum[curr] = 1

    paths += (
        count_running_helper(root.left, target_value, running_sum, curr) +
        count_running_helper(root.right, target_value, running_sum, curr))

    running_sum[curr] -= 1
    curr -= root.val
    return paths


# test
t = random_tree(15)
tree = t.negative  # generates a tree with negative vals

print("Using brute force: {}".format(count_paths(tree, 10)))
print("Using running sum: {}".format(count_paths_running_sum(tree, 10)))
    return list_of_lists


def list_of_depth_bfs(root):
    if not root:
        return None

    final_list = []
    curr = [root]

    while len(curr) > 0:
        final_list.append(curr)
        parents = curr
        curr = []
        for node in parents:
            if node.right:
                curr.append(node.right)
            if node.left:
                curr.append(node.left)

    return final_list


# TEST
t = random_tree()
root = t.balanced

print("DFS: {}".format(list_of_depth(root)))
print("BFS: {}".format(list_of_depth_bfs(root)))
        return root
    if l:
        return common_helper(root.left, a, b)
    return common_helper(root.right, a, b)


def covers2(root, a, b):
    if not root:
        return False
    if root is a or root is b:
        return True
    return covers2(root.left, a, b) or covers2(root.right, a, b)


# test
t = random_tree(10)
root = t.balanced
seven = root.right
five = seven.left
eight = seven.right
nine = eight.right
six = five.right
one = root.left
zero = one.left
two = one.right
three = two.right
print("First two algorithms have a link to thier parent node")
print("Nodes 8,9 shoud return 7: {}".format(common_parent(nine, eight)))
print("Nodes 4,0 shoud return None: {}".format(common_parent(root, zero)))
print("Nodes 0,2 shoud return 1: {}".format(common_parent(zero, two)))
print("Nodes 0,3 shoud return 1: {}".format(common_parent(zero, three)))