return root.val else: # Leaf Node # smaller and has value # case 1 parent = root.parent while parent and parent.val < root.val: parent = parent.parent else: # TOREAD # parent may be None if parent and parent.val > root.val: return parent.val else: #case 2 last element return None elif root.val < target: root = root.right else: root = root.left return None if __name__ == '__main__': tree = build_tree_with_parent([100, 50, 200, 25, 75, 125, 350]) print_tree(tree) print print inorder_success_bst_with_parent(tree, 350)
res = find_n_rec(root.right, n) if res: return res global cur_count cur_count += 1 if n == cur_count: return root.val res = find_n_rec(root.left, n) if res: return res return return find_n_rec(bst, nth) if __name__ == '__main__': binary_search_tree = \ build_tree([100, 50, 200, 25, 75, 125, 350]) print_tree(binary_search_tree) val = find_nth_highest(binary_search_tree, 3) print print 'nth highest is: ' + str(val) assert 125 == val print better_solve1(binary_search_tree, 3) print better_solve2(binary_search_tree, 3)
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)
from helper import build_tree from helper import print_tree def transfer(root): tree = root visited = [root] while len(visited): root = visited.pop() if root.left: root.left.parent = root visited.append(root.left) # TOREAD: this is not elif # be careful, elif only when the first one is not right if root.right: root.right.parent = root visited.append(root.right) return tree if __name__ == '__main__': tree = build_tree([100, 50, 200, 25, 75, 125, 350]) print_tree(tree) root = transfer(tree) print_tree(root)