# 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))