Problem 28 · Trees
Serialize and Deserialize Binary Tree
01Problem
Design functions that serialize a binary tree to a string and deserialize that string back into an identical tree.
02Key insight
Pre-order with explicit null markers fully determines the tree; deserialize by consuming tokens from an iterator in the same pre-order.
03Solution
Try it first.
TimeO(n)
SpaceO(n)
tests.py · 5 passing
tests.pypython12 lines
T = TreeNode
root = T(1, T(2), T(3, T(4), T(5)))
assert serialize(root) == "1,2,#,#,3,4,#,#,5,#,#"
assert deserialize(serialize(root)) == root
assert deserialize(serialize(None)) is None
neg = T(-10, None, T(-20))
assert deserialize(serialize(neg)) == neg
deep = None
for v in range(1500):
deep = T(v, deep)
s = serialize(deep)
assert serialize(deserialize(s)) == s # 1500-deep skewed tree, no RecursionError04Staff-level follow-up
Payload size and versioning matter? Use a length-prefixed binary format or protobuf with a schema version; for BSTs drop null markers entirely since pre-order alone plus bounds reconstructs the tree.