Technique · Interview · medium
Tree Hashing / Canonical Forms
Give each subtree a canonical id: map its sorted tuple of child ids through a hash map, or use a randomised polynomial hash. Equal shapes then get equal ids. Unrooted trees are compared by rooting at their centre(s).
0%
mastery
0/4 solved
0/4 solved
Recognise it
The signal
find duplicate subtrees
1Brute force
Compare every pair of subtrees: O(n2) or worse.
2The observation
Repeated structural comparison.
3Why it works
Two rooted subtrees are isomorphic iff their canonical ids are equal. This is exact with the map-of-sorted-children method.
Reach for it when
- +are two trees isomorphic (rooted or unrooted)
- +count distinct subtree shapes
Not when
- ×you need the actual node matching (record it while merging ids)
Practice
0/4 solved
- Subtree of Another TreeMeta, AmazonEasy
- Find Duplicate SubtreesMedium
- Tree Isomorphism ICSESMedium
- Tree Isomorphism IICSESMedium
Pitfalls
Misconceptions
- !serializing without separators/null markers causes collisions
- !for unrooted trees, root at the centre and try both centres when there are two
Go deeper1 combinations · resources
Combinations
Tree Hashing / Canonical Forms+Topological Sort
are two unrooted trees isomorphic
- Tree Hashing / Canonical Forms:
- a canonical id of the tree rooted at each centre
- Topological Sort:
- leaf trimming finds the 1-2 centres of an unrooted tree