Proofs: BK-tree
These are the human proofs of BK-tree, at full length.
The BK-tree keeps its invariant and answers range and nearest queries exactly full
This proof shows: correctness.
Let be a metric space with . So if and only if , is symmetric, and .
Invariant (B). For each node and each key of , every item in the subtree of has .
Lemma 1. INSERT keeps (B) and stores no item twice.
Proof. Let be the nodes visited, with the root. For , INSERT moves from to with , and at it either returns at line L4 or adds as . In the second case, lies in the subtree of key of each and has distance to , so (B) holds for at every ancestor. No other node gains or loses an item. If an equal item is stored, it lies on the path of : by induction, if is in the subtree of , then , so is or lies in the subtree of . So INSERT reaches the node of and returns at line L4.
Lemma 2. If is in the subtree of , then for every .
Proof. By (B), . The triangle inequality gives and . With symmetry, these two inequalities say .
Theorem 1. RANGE reports exactly the items in the subtree of with , each once.
Proof. By induction on the height of . For $t = $ nil there is nothing to report. Otherwise, line L7 reports if and only if . Every other item of the subtree lies in exactly one child subtree, say of key . If , Lemma 2 gives , so line L8 calls RANGE on that child, and by induction the call reports once. If the child is not called, no item in it is within . Items of called children with are not reported, by induction.
Theorem 2. NEAREST returns and an item with , if is not empty.
Proof. We show that the loop keeps the following invariant (N): for each stack entry , every item of the subtree of is at distance at least from ; and every item of is in the subtree of a stack entry, or has been evaluated at line L11, or is at distance at least from .
At the start, the stack holds , and (N) holds. Pop . If , every item of the subtree of is at distance at least , so dropping the entry keeps (N). Otherwise line L11 evaluates , and lowers only to the distance of an evaluated item; items earlier covered by "at least " remain at least the new, smaller . Each child of key is pushed with bound , which is a lower bound for its subtree by Lemma 2. A child with is not pushed, and all of its items are at distance at least by Lemma 2. So (N) holds after the step.
Each node is pushed at most once, since it is pushed only by its parent when the parent is evaluated, so the loop ends. Then the stack is empty, and by (N) every item is evaluated or at distance at least . Since is the least distance among evaluated items and is an item with that distance, is the minimum over .