FrontendInterviews.dev

Loading problem…

80. Serialize/Deserialize Binary Tree - State Persistence

Hard•
Acceptance: 89.47%
•
🔓3/3 Pro unlocks today

You're building a form builder or state management system that needs to persist complex nested state (a tree) to localStorage or send it over an API.

Implement two functions:

  • serialize(root) → returns a string representation of the binary tree
  • deserialize(data) → reconstructs the original tree from the string

There is no restriction on the encoding format, but it must satisfy:

  • deserialize(serialize(root)) reconstructs the same structure and values.
  • Must handle null children.

Canonical format for this problem

Use level-order (BFS) values separated by commas, using the literal string "null" for missing nodes.

For stability, trim trailing `null`s in the serialized output.

Example

Tree: [1,2,3,null,null,4,5]

Serialized: "1,2,3,null,null,4,5"

Real-World Context

  • Form state: Persist nested form schemas
  • API transfer: Send trees over the network
  • localStorage: Save/restore UI state
  • State hydration: Serialize app state snapshots

Examples

Example 1:

Input: serialize([1,2,3,null,null,4,5])
Output: 1,2,3,null,null,4,5
Explanation:
Level-order traversal with 'null' markers; trailing 'null's are trimmed.

Example 2:

Input: deserialize("1,2,3,null,null,4,5")
Output: [1,2,3,null,null,4,5]
Explanation:
Reconstructs the original tree.

Example 3:

Input: serialize([])
Output:
Explanation:
Empty tree serializes to empty string.

Example 4:

Input: deserialize("")
Output: []
Explanation:
Empty string deserializes to an empty tree.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -1000 <= Node.val <= 1000
  • Must preserve structure exactly (including missing children).
  • Serialized format must be deterministic (trim trailing nulls).