Data Structures19 sections · 729 units
Open in Course

Sharing Unchanged Subtrees

Why it's efficient

Path copying shares unchanged subtrees between versions. If you update one leaf in a tree of nn nodes:

  • Path length: O(logn)O(\log n) for balanced trees
  • New nodes created: O(logn)O(\log n)
  • Shared nodes: nO(logn)n - O(\log n)

After mm updates:

  • Total nodes: O(n+mlogn)O(n + m \log n)
  • Each version still has nn "logical" nodes

This is dramatically better than O(nm)O(nm) for full copies.

Here's the trick: immutability enables sharing. If a subtree never changes, all versions can point to the same physical subtree.