from implementations.tree import BinaryTreeNode def binary_tree_paths(root): return list(_binary_tree_paths(root)) def _binary_tree_paths(root): if root.left: for path in _binary_tree_paths(root.left): yield '%s->%s' % (root.value, path) if root.right: for path in _binary_tree_paths(root.right): yield '%s->%s' % (root.value, path) if root.left is None and root.right is None: yield root.value if __name__ == '__main__': tree = BinaryTreeNode(4) tree.left = BinaryTreeNode(2) tree.left.left = BinaryTreeNode(1) tree.right = BinaryTreeNode(7) tree.right.left = BinaryTreeNode(6) tree.right.right = BinaryTreeNode(9) print binary_tree_paths(tree)
""" Write a function to check if two trees have the same structure and the same elements. """ from implementations.tree import BinaryTreeNode def equal(tree1, tree2): if tree1 is None and tree2 is None: return True elif tree1 is None or tree2 is None: return False return tree1.value == tree2.value and equal(tree1.left, tree2.left) and equal(tree1.right, tree2.right) if __name__ == "__main__": tree1 = BinaryTreeNode(4) tree1.left = BinaryTreeNode(2) tree1.left.left = BinaryTreeNode(1) tree1.right = BinaryTreeNode(7) tree1.right.left = BinaryTreeNode(6) tree1.right.right = BinaryTreeNode(9) tree2 = BinaryTreeNode(4) tree2.left = BinaryTreeNode(2) tree2.left.left = BinaryTreeNode(1) tree2.right = BinaryTreeNode(7) tree2.right.left = BinaryTreeNode(6) tree2.right.right = BinaryTreeNode(9) print equal(tree1, tree2)