if root1 is None and root2 is None: return True # if root1.val == root2.val: # return dfs(root1.left, root2.left) and \ # dfs(root1.right, root2.right) # else: # return False # TOREAD: better wrote if root1 is not None and root2 is not None: return (root1.val == root2.val) and \ dfs(root1.left, root2.left) and \ dfs(root1.right, root2.right) else: return False return dfs(tree1, tree2) if __name__ == '__main__': tree1 = tree2 = build_tree([100, 50, 200, '#', 25, 125, 350]) print_tree(tree1) assert True == check_identical_trees(tree1, tree2) tree1 = build_tree([100, 50, 200, '#', 25, 125, 350]) tree2 = build_tree([100, 50, 200, '#', 25, 125, 250]) print_tree(tree1) print_tree(tree2) assert False == check_identical_trees(tree1, tree2)
def iter_inorder(tree): # visit == print # left, root, right root = tree stack = [] nodes = [] while len(stack) or root is not None: if root is not None: stack.append(root) root = root.left continue # TOREAD: process it and git rid of it at last nodes.append(stack[-1].val) root = stack[-1].right stack.pop() print print nodes if __name__ == '__main__': tree = build_tree([100, 50, 200, 25, 75, 125, 350]) print_tree(tree) order = [25, 50, 75, 100, 125, 200, 350] iter_inorder(tree)
from helper import build_tree from helper import print_tree def mirror_tree(root): # post order swap def swap_node(root): if not root: return swap_node(root.left) swap_node(root.right) root.left, root.right = root.right, root.left return swap_node(root) if __name__ == '__main__': tree = build_tree([20, 50, 200, 25, 75, '#', 300]) print_tree(tree) print mirror_tree(tree) print_tree(tree)
from helper import build_tree from helper import print_tree def delete_zero_sum_in(tree): def sub_sum_tree(root): if root is None: return 0 # TOREAD: post order search left_sum = sub_sum_tree(root.left) right_sum = sub_sum_tree(root.right) # TOREAD: just some process different than tree sum if left_sum == 0: root.left = None elif right_sum == 0: root.right = None return root.val + left_sum + right_sum return sub_sum_tree(tree) if __name__ == '__main__': tree = build_tree([7, 5, 6, -3, -2, '#', '#']) print_tree(tree) delete_zero_sum_in(tree) print_tree(tree)