def solution(t1, t2):
    l1 = BinaryTree.get_list_representation(t1.root)
    l2 = BinaryTree.get_list_representation(t2.root)
    sum_list = [
        fail_safe_add(x, y)
        for x, y in itertools.zip_longest(l1, l2, fillvalue=None)
    ]
    return BinaryTree.build_tree_from_list(sum_list)
예제 #2
0
# Same Tree
# Given two binary trees, write a function to check if they are the same or not.
from data_structures.binary_tree import BinaryTree


def solution(p, q):
    if p is None and q is None:
        return True
    elif p is None and q is not None:
        return False
    elif p is not None and q is None:
        return False
    else:
        if p.value == q.value:
            return solution(p.left, q.left) and solution(p.right, q.right)
        else:
            return False


if __name__ == '__main__':
    list1 = [1, 2, 3]
    list2 = [1, 2, 3]

    p = BinaryTree.build_tree_from_list(list1)
    q = BinaryTree.build_tree_from_list(list2)
    print("Are trees the same: ", solution(p.root, q.root))
# Invert a Binary Tree
# "Google: 90% of our engineers use the software you wrote (Homebrew),
# but you can’t invert a binary tree on a whiteboard so f*** off."
from data_structures.binary_tree import BinaryTree

def solution(root):
    if not root:
        return root

    tmp_node = root.left
    root.left = root.right
    root.right = tmp_node
    solution(root.left)
    solution(root.right)
    return root


if __name__ == '__main__':
    tree = BinaryTree.build_tree_from_list([4, 2, 7, 1, None, 6, 9])
    BinaryTree.level_order_traversal(tree.root)
    inverted_tree = solution(tree.root)
    BinaryTree.level_order_traversal(inverted_tree)

def fail_safe_add(x, y):
    if x and y:
        return x + y
    elif x:
        return x
    elif y:
        return y
    else:
        return None


def recursive_solution(t1, t2):
    if not t1:
        return t2
    if not t2:
        return t1
    t1.value = fail_safe_add(t1.value, t2.value)
    t1.left = recursive_solution(t1.left, t2.left)
    t1.right = recursive_solution(t1.right, t2.right)
    return t1


if __name__ == '__main__':
    t1 = BinaryTree.build_tree_from_list([1, 3, 2, 5])
    t2 = BinaryTree.build_tree_from_list([2, 1, 3, None, 4, 7])
    # merged_tree = solution(t1, t2)
    # BinaryTree.level_order_traversal(merged_tree.root)
    BinaryTree.level_order_traversal(recursive_solution(t1.root, t2.root))