Serialise and deserialise
A tree can be written as a string by preorder with a marker for each empty child, and read back by the same preorder. The same idea gives every subtree a key string, so equal subtrees have equal keys, which finds duplicate subtrees with a hash map in one pass.
How to recognise it
- A tree must be stored or sent as text and rebuilt.
- You need to tell whether two subtrees are equal, many times.
- Duplicate or repeated subtrees.
Write and read the same way
serialize(n): n is null -> "#"; else n.val + "," + serialize(n.left) + "," + serialize(n.right)
deserialize: read a token; "#" -> null; else make a node, read its left, then its right
What a node, a child, a leaf and a level are is on the Structures page.
Keys for subtrees
A post-order walk can build a key for every subtree from its children's keys:
key(n) = "(" + n.val + "," + key(left) + "," + key(right) + ")". Count keys in a hash map; a key seen twice is a
duplicate subtree.
Common mistakes
- Leaving out the empty markers.
- Building keys without separators, so "1" + "23" and "12" + "3" look the same.
Problems
- Check if a Binary Tree contains duplicate subtrees of size 2 or moremediumguide ready
- Find all Duplicate subtrees in a Binary treemediumguide ready
- Serialize and Deserialize Binary Treehardguide ready