AlgoViz

Serialize and Deserialize Binary Tree

Medium

Preorder with null markers

Problem

Encode a binary tree to a string and decode it back exactly.

In simple words

Write the tree with markers for nulls (e.g. preorder); reading it back reconstructs the same tree.

The idea

Emit a preorder traversal that writes an explicit marker for every missing child, which makes the encoding unambiguous. Reading the tokens back in the same order rebuilds the identical tree.

The trick

  • Without null markers the structure cannot be recovered.
  • Deserialise with a moving index consuming tokens in preorder.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

1
2
3
4
5
0
1
2
3
4

Step 1 of 2. Here's the example — [1,2,3,null,null,4,5] Values: 1, 2, 3, 4, 5.

1/2
Optimal
timeO(n)spaceO(n)
1serialize: preorder with '#' for null2deserialize: read tokens rebuilding recursively

Input

array
[1, 2, 3, 4, 5]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
tree = [1,2,3,null,null,4,5]
Output:
"1,2,3,#,#,4,5"
Explanation:
Flatten to a string, then rebuild it exactly.

Example 2

Input:
tree = [1]
Output:
"1"
Explanation:
One node.

Example 3

Input:
tree = []
Output:
"(empty)"
Explanation:
Empty tree serializes to nothing.

Finished the walkthrough? Add it to your streak.