Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2013/functional-programming-design-and-analysis-of-algorithms/4/g/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2013 Functional programming, design and analysis of algorithms 4 g Solution by
Codex 0 2026-10-31
Search as for insertion. Removing a node with at most one nonempty child leaves that child in its place. With two children, use the smallest key in the right subtree as the replacement and remove that occurrence from the right subtree:
delete :: Ord a => a -> STree a -> STree a
delete _ Empty = Empty
delete y (Node left x right) =
case compare y x of
LT -> Node (delete y left) x right
GT -> Node left x (delete y right)
EQ -> join left right
where
-- Join two search trees with every left key below every right key.
join :: STree a -> STree a -> STree a
join Empty r = r
join l Empty = l
join l r = let (smallest, rest) = takeMin r
in Node l smallest rest
-- Precondition: the input tree is nonempty.
takeMin :: STree a -> (a, STree a)
takeMin Empty = error "takeMin: empty tree"
takeMin (Node Empty x right) = (x, right)
takeMin (Node left x right) =
let (smallest, rest) = takeMin left
in (smallest, Node rest x right)The call to
takeMin occurs only after both empty cases have been excluded. Its structural recursion follows left children until it reaches the minimum label and rebuilds the path with that occurrence removed.For a matching label and successor , all left labels are below , while every label remaining on the right is strictly above . Thus replacing by preserves the binary search tree invariant. Every other branch preserves the invariant by structural induction. The resulting set is exactlyWhether the key is absent or present, untouched subtrees can be shared. The search path followed by the successor path uses time and fresh nodes for original height of a binary tree , so the worst case is without balancing. This is persistent binary search tree deletion: the original value remains available.
New to topics? Read the docs here!