Serialize and Deserialize Binary Tree (BFS)

Hard~35 min

Design an algorithm to serialize a binary tree into a string, and deserialize that string back into the original tree, using BFS (level-order traversal).

Serialization is the process of converting a data structure into a sequence of characters so that it can be stored or transmitted and reconstructed later.

You need to implement a Codec class (or equivalent) with two methods:

  • serialize(root) — Encodes a tree to a single string using BFS.
  • deserialize(data) — Decodes the string back to a tree using BFS.

Your serialization/deserialization algorithm should work correctly — the tree reconstructed from deserialize(serialize(root)) must be structurally identical to the original tree with the same node values.

There is no restriction on how your serialization format works. Any valid format is accepted as long as the round-trip produces the correct tree.

Hint: Think about how BFS visits nodes level by level. If you record each node's value (and use a sentinel for null children), you capture the full tree structure. Deserialization can then rebuild the tree by reading tokens in the same level-order sequence.

The tree is given as a level-order array where null represents a missing node. For example, [1,2,3,null,null,4,5] represents:

      1
     / \
    2   3
       / \
      4   5

Examples

Example 1
Input: root = [1, 2, 3, null, null, 4, 5]
Output: [1, 2, 3, null, null, 4, 5]
Explanation: The tree is serialized to a string using BFS, then deserialized back. The reconstructed tree matches the original, producing the same level-order array.
Example 2
Input: root = []
Output: []
Explanation: An empty tree serializes and deserializes back to an empty tree.
Example 3
Input: root = [1]
Output: [1]
Explanation: A single-node tree round-trips correctly.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4]
  • -1000 <= Node.val <= 1000
  • Your serialize and deserialize functions must be inverses of each other
  • Expected time complexity: O(n)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run