Sub topic 5
Path copying: copy only the route to the change
This chapter assumes you can read Python and basic JavaScript, know how trees and references work, and are comfortable with Big-O notation. You have already seen that two versions of a structure can share nodes. Here you will learn the rule that makes this safe: path copying.
The idea
A persistent structure never changes a node after it is built. To "change" a value deep inside a tree, you must build a new version. Path copying does this with one rule:
- Copy the node that holds the change.
- Copy its parent, so the parent can point to the new copy.
- Keep copying parents up to the root.
- Reuse every other node as it is.
The nodes you copy form the path from the root to the change. Every node off that path is untouched, so the new version points at the same objects as the old one. The old root still leads to the old nodes, so the old version stays valid.
Why the parents must be copied
A node cannot be edited, and a child's address changes when you copy it. The parent stores that address, so the parent needs a new field value. It therefore has to be a new node too. The same reasoning applies to the grandparent, and so on up to the root. The chain only stops at the root, which becomes the handle for the new version.
In the diagram, C and D have two parents each. That is structural sharing at work.
A runnable example
The function below replaces the value at a position given as a string of "L" and "R" steps. It builds new nodes on the way back up the recursion.
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Node:
value: int
left: Optional["Node"] = None
right: Optional["Node"] = None
def set_at(node: Node, path: str, value: int) -> Node:
if not path:
return Node(value, node.left, node.right)
step, rest = path[0], path[1:]
if step == "L":
return Node(node.value, set_at(node.left, rest, value), node.right)
return Node(node.value, node.left, set_at(node.right, rest, value))
t1 = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6), Node(7)))
t2 = set_at(t1, "LR", 50)
assert t2.right is t1.right # sibling subtree shared
assert t2.left.left is t1.left.left # sibling leaf shared
assert t2.left is not t1.left # parent on the path copied
assert t2 is not t1 # root copied
assert t2.left.right.value == 50 # new version has the change
assert t1.left.right.value == 5 # old version is intactThe update visits the root, its left child, and that child's right child. It allocates three new nodes. The tree has seven nodes, and four are reused.
The same pattern in JavaScript
Spread syntax gives you path copying by hand for nested objects. You write out the path yourself.
const state = { user: { profile: { name: "Ada" }, id: 1 }, items: [1, 2] };
const next = {
...state,
user: { ...state.user, profile: { ...state.user.profile, name: "Grace" } },
};
console.log(next.items === state.items); // true: shared
console.log(next.user.id === state.user.id); // true: same primitive
console.log(next.user === state.user); // false: on the path
console.log(next.user.profile === state.user.profile); // false: on the path
console.log(state.user.profile.name); // "Ada"The copying is shallow at each level. Each spread copies one object's fields, not the objects they refer to.
Cost
Path copying costs time and memory proportional to the length of the path. For a balanced binary tree with n nodes, that is O(log n) new nodes per update. Full copying would cost O(n). For an unbalanced tree, the path can be as long as n, so balance matters.
Common errors
- Mutating a shared node. If you assign to a field of a node that two versions share, both versions change. Use frozen dataclasses, named tuples, or
Object.freezeto catch this. - Forgetting to copy a parent. If you build a new child but attach it to the old parent by mutation, the old version now sees the change.
- Copying too much. Deep-copying the whole structure (for example with
copy.deepcopy) throws away sharing and costs O(n). - Assuming the root alone is the version. The root is the handle, but a version is every node reachable from it.
Exercise
A balanced persistent binary tree has 1,000,000 nodes and a depth of about 20. How many new nodes does one path-copying update allocate, and why is the old version still valid?
Show answer
About 20 to 21 new nodes, one for each node on the path from the root to the changed node. The old version is still valid because none of its nodes were modified. The old root still points to the old path nodes, and the new root points to the copies plus the shared untouched subtrees.