Turn a binary tree into a string and back. Write it in preorder with a marker for every missing child, then read it back the same way.
▼The problem
LeetCode 297 (Hard). Design an algorithm to serialize a binary tree to a string and deserialize that string back to the original tree structure. Any format works, as long as deserialize(serialize(root)) gives back the same tree.
Example (LeetCode's): root = [1,2,3,null,null,4,5] round-trips to [1,2,3,null,null,4,5]; root = [] to [].
The solution
def serialize(root):
if not root:
return '#'
left = serialize(root.left)
right = serialize(root.right)
return f'{root.val},{left},{right}'
def deserialize(data):
tokens = iter(data.split(','))
def build():
tok = next(tokens)
if tok == '#':
return None
node = TreeNode(int(tok))
node.left = build()
node.right = build()
return node
return build()Transcript
Serialize and Deserialize Binary Tree. Turn a binary tree into a string, then turn that string back into the very same tree: same values, same shape.
Here's our tree: one on top, children two and three, and three has four and five below it. Pack it, unpack it, and every node must land in the same place.
The easy way: write just the values, in preorder: one, two, three. But a chain, three under two under one, also writes one, two, three. Two trees, one string. Values alone lose the shape.
The fix: write the gaps too. Picture threading beads on a string. Walk in preorder: the node, then its left side, then its right. Each value is a bead; each missing child is a black hash bead. Now the two trees thread differently.
In code, serialize returns a hash for an empty node; otherwise the value, then the left side, then the right, joined by commas. To deserialize, split on commas and read tokens with an iterator. A hash means None. Anything else makes a node, then builds its left, then its right.
Let's thread our tree. One, then left to two. Two has no children: hash, hash. Then three, and left to four: hash, hash. Then five: hash, hash. Eleven beads: five values, six gaps.
Now unthread it, in the same order. One is the root. Two hangs on its left. Hash, hash: two has no children. Three hangs right of one. Four hangs left of three; two hashes close it. Five hangs right, closed by two more. Same tree. An empty tree is just one hash.
A tree with n nodes has n plus one gaps, so the string holds two n plus one tokens, each written once and read once: order n time, both ways, and order n space. LeetCode's own format, level order with a queue, works too.
Thread in preorder, mark every gap, rebuild in the same order. That's Serialize and Deserialize Binary Tree.