Skip to main content
HardAlgorithms & Data StructuresDesign

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 st...

What you will practice

PythonArrays & StringsTreeRecursionSerializationDesign

Requirements

  • Implement `serialize(root)` taking a `TreeNode | None` and returning a `str`.
  • Implement `deserialize(data)` taking the string produced by `serialize` and returning a `TreeNode | None`.
  • An empty tree (`None`) must round-trip cleanly: `deserialize(serialize(None))` returns `None`.
  • Structure must be preserved, not just values. Trees with the same values arranged differently must serialize to different strings.
  • Do not modify the provided `TreeNode` class. Tests construct trees by hand and rely on its shape.

Starter files

main.pyEditable starter

What the judge checks

  • Runs in the python environment with the python-pytest runner.
  • Uses a 6000ms judge budget.
  • Behavior rules include: Round Trip Empty Tree, Round Trip Single Node, Round Trip Balanced Tree, Round Trip Left Leaning Chain.

Constraints

  • `serialize` and `deserialize` must be inverses for any binary tree the tests pass in.
  • Use only the standard library (`json` is fine if you want it).
  • Treat the encoding as opaque — tests only call `serialize` and `deserialize`, never inspect the string itself.

Example behavior

Input
       1
      / \
     2   3
        / \
       4   5
Output
deserialize(serialize(root)) reproduces the same five-node tree (structurally identical).
Input
Left-leaning chain: 1 → 2 (left) → 3 (left) → 4 (left)
Output
Round trip preserves the chain — none of the nodes get duplicated into the right side.

Follow-up

How would you handle very large trees that can't be loaded into a single string in memory? What changes about the encoding?