Serialize and Restore a Saved Navigation Tree
You're persisting users' saved navigation trees — folders, sub-folders, bookmarks — into flat strings so they can be stored as a single blob and replayed later.
Write serialize(root) that turns a binary tree into a string, and deserialize(data) that rebuilds the original tree from that string. The judge does not check your encoding format — it checks the round trip: for every test tree, deserialize(serialize(tree)) must produce an identical tree.
You pick the format. Anything goes — preorder + null markers, level-order BFS with a delimiter, JSON, your own scheme — as long as the round trip is exact.
- Implement
serialize(root)taking aTreeNode | Noneand returning astr. - Implement
deserialize(data)taking the string produced byserializeand returning aTreeNode | None. - An empty tree (
None) must round-trip cleanly:deserialize(serialize(None))returnsNone. - Structure must be preserved, not just values. Trees with the same values arranged differently must serialize to different strings.
- Do not modify the provided
TreeNodeclass. Tests construct trees by hand and rely on its shape.
1
/ \
2 3
/ \
4 5deserialize(serialize(root)) reproduces the same five-node tree (structurally identical).
Left-leaning chain: 1 → 2 (left) → 3 (left) → 4 (left)
Round trip preserves the chain — none of the nodes get duplicated into the right side.
1
/ \
2 2 (duplicate values at different positions)After round trip, the two `2` nodes are still distinct children of `1`.
serializeanddeserializemust be inverses for any binary tree the tests pass in.- Use only the standard library (
jsonis fine if you want it). - Treat the encoding as opaque — tests only call
serializeanddeserialize, never inspect the string itself.
How would you handle very large trees that can't be loaded into a single string in memory? What changes about the encoding?
Keep moving through related algorithms & data structures problems and build a stronger search-friendly practice loop around this topic.
View track →