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) pointer = pointer.nxt
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 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)