Sub topic 12
Inserting, deleting and rebuilding k-d trees
This chapter assumes you can build a k-d tree by median split and run nearest-neighbor search on it. It also assumes you are comfortable with binary search tree deletion. Here you will see how to change a tree after it is built, and when to rebuild it instead.
Insertion: descend and attach a leaf
Insertion works like a binary search tree insert. At each node you compare one coordinate, chosen by the node's axis, and go left or right. When you reach an empty slot, you put a new node there. The new node's axis is its depth modulo the number of dimensions.
This tree uses one convention: the left subtree holds coordinates less than or equal to the node's, and the right subtree holds coordinates greater than or equal to it. The median build produces equal keys on the left, so insertion sends ties right and deletion must tolerate both sides.
Insertion costs O(depth). Nothing rebalances the tree, so the depth depends on the insertion order.
Deletion: replace from a subtree
Deleting a leaf is easy. Deleting an inner node is harder, because its children are split on different axes at different levels. You cannot just promote a child. Instead, replace the node's point with a point that keeps the invariant for its axis.
- If the right subtree exists, take its minimum along the node's axis. Make that point the new node point, then delete it from the right subtree.
- Otherwise, if the left subtree exists, take its minimum along the node's axis. Make that point the new node point, move the remaining left subtree to the right, and set left to empty.
- If the node is a leaf, remove it.
Finding a minimum on the node's axis is cheap only when the subtree splits on that same axis. Then you follow left children. At a level that splits on another axis, either side may hold the minimum, so you must check both. This makes deletion more expensive than insertion. It costs O(n^(1-1/k)) in the worst case for k dimensions.
The code below assumes all points are distinct.
import math
class Node:
def __init__(self, point, axis, left=None, right=None):
self.point, self.axis = point, axis
self.left, self.right = left, right
def build(points, depth=0):
if not points:
return None
axis = depth % len(points[0])
points = sorted(points, key=lambda p: p[axis])
mid = len(points) // 2
return Node(points[mid], axis,
build(points[:mid], depth + 1),
build(points[mid + 1:], depth + 1))
def insert(node, point, depth=0):
if node is None:
return Node(point, depth % len(point))
if point[node.axis] < node.point[node.axis]:
node.left = insert(node.left, point, depth + 1)
else:
node.right = insert(node.right, point, depth + 1)
return node
def find_min(node, axis):
if node is None:
return None
if node.axis == axis:
if node.left is None:
return node.point
return find_min(node.left, axis)
candidates = [node.point]
for child in (node.left, node.right):
found = find_min(child, axis)
if found is not None:
candidates.append(found)
return min(candidates, key=lambda p: p[axis])
def delete(node, point):
if node is None:
return None
if node.point == point:
if node.right is not None:
node.point = find_min(node.right, node.axis)
node.right = delete(node.right, node.point)
elif node.left is not None:
node.point = find_min(node.left, node.axis)
node.right = delete(node.left, node.point)
node.left = None
else:
return None
return node
c, v = point[node.axis], node.point[node.axis]
if c <= v:
node.left = delete(node.left, point)
if c >= v:
node.right = delete(node.right, point)
return node
def to_list(node):
if node is None:
return []
return [node.point] + to_list(node.left) + to_list(node.right)
def height(node):
return 0 if node is None else 1 + max(height(node.left), height(node.right))
tree = build([(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)])
tree = insert(tree, (6, 5))
tree = delete(tree, (7, 2))
print(to_list(tree)) # [(8, 1), (5, 4), (2, 3), (4, 7), (6, 5), (9, 6)]
skewed = None
for i in range(1, 16):
skewed = insert(skewed, (i, i))
print(height(skewed)) # 15
if height(skewed) > 2 * math.log2(15 + 1):
skewed = build(to_list(skewed))
print(height(skewed)) # 4Rebuilding to restore balance
Inserting sorted points, as in the last example, turns the tree into a linked list. Queries then cost O(n). Deletion by replacement can also skew the tree.
The simplest fix is to rebuild. Collect all points, then call build. This costs O(n log n) with the sorting build. Trigger it when the height exceeds a multiple of log2(n), as above. Alternatively, rebuild after a fixed number of updates, such as n/2.
Rebuilds happen rarely, so their cost spread over many updates is small. If your data arrives in batches, use another option: keep a few trees of growing sizes and merge them as they fill (the logarithmic method). Another option is a scapegoat-style rebuild of only the lopsided subtree.
Exercise
You insert 1,000 points that arrive sorted by x into a 2-d k-d tree, with no rebuild. What is the tree's height, and what do nearest-neighbor queries cost?
Show answer
The x-axis levels send every new point right, so the tree degenerates. The height approaches 1,000 and queries cost O(n), the same as a linear scan. Rebuilding with build gives a height of about log2(1000), roughly 10.