new_finish = current if left_list: left_list[1].nxt = current current.prv = left_list[1].nxt new_start = left_list[0] if right_list: right_list[0].prv = current current.nxt = right_list[0] new_finish = right_list[1] return new_start, new_finish root = BstNode(10) root.left = BstNode(5) root.right = BstNode(15) root.left.left = BstNode(2) root.left.right = BstNode(7) root.right.left = BstNode(12) root.right.right = BstNode(17) sorted_list = convert_bst_to_list(root) pointer = sorted_list while pointer: print(pointer.value)
if left_result.max <= result.min: result.size += left_result.size result.min = left_result.min result.res = max(result.res, max(result.size, left_result.res)) if tree.right: right_result = largest_bst_subtree(tree.right) if right_result.min >= result.max: result.size += right_result.size result.max = right_result.max result.res = max(result.res, max(result.size, right_result.res)) return result root = BstNode(50) root.left = BstNode(30) root.right = BstNode(60) root.left.left = BstNode(5) root.left.right = BstNode(20) root.right.left = BstNode(45) root.right.right = BstNode(70) root.right.right.left = BstNode(65) root.right.right.right = BstNode(80) print(largest_bst_subtree(root).res)
def common_ancestor_constant_space(root, first, second): if root is None: return None if root.value == first or root.value == second: return root left = common_ancestor_constant_space(root.left, first, second) right = common_ancestor_constant_space(root.right, first, second) if left and right: return root return left if left is not None else right root = BstNode(9) root.left = BstNode(5) root.right = BstNode(15) root.left.left = BstNode(3) root.left.right = BstNode(7) root.right.left = BstNode(12) root.right.right = BstNode(20) print(common_ancestor_linear_space(root, 3, 7).value) print(common_ancestor_constant_space(root, 3, 7).value)
if tree.left.max_path_down > 0: tree.max_path_down += tree.left.max_path_down tree.max_paths_down += tree.left.max_path_down max_left = tree.left.max_paths_down if tree.right is not None: max_weight_path_in_tree(tree.right) if tree.right.max_path_down > 0: tree.max_path_down = max(tree.max_path_down, tree.value + tree.right.max_path_down) tree.max_paths_down += tree.right.max_path_down max_right = tree.right.max_paths_down return max(max_left, tree.max_paths_down, max_right) root = BstNode(1) root.left = BstNode(0) root.right = BstNode(10) root.left.left = BstNode(100) root.left.right = BstNode(30) root.right.right = BstNode(90) root.right.right.left = BstNode(10) print(max_weight_path_from_root(root))