hardTreesPure DSA~34 min
Snapshot And Restore A Tree
To persist an in-memory configuration tree across restarts, you must serialise it to a flat string and later rebuild the exact same structure from that string.
Problem
Design serialize and deserialize for a binary tree. serialize encodes a tree to a single string; deserialize reconstructs the identical tree from that string. The structure and values must round-trip exactly.
Input
A binary tree of up to 10^4 nodes; node values fit in 32-bit ints (may be negative).
Output
serialize → a string; deserialize → the reconstructed tree root.
Constraints
- deserialize(serialize(root)) must equal the original tree
- Handle null children explicitly so structure is preserved
- Up to 10,000 nodes
Examples
Example 1
Input
root = [1,2,3,null,null,4,5]
Output
[1,2,3,null,null,4,5]
Round-trips to the same tree; the right child of 1 has children 4 and 5.
Example 2
Input
root = []
Output
[]
An empty tree serialises and restores as empty.