Serialize and Deserialize a Binary Tree

Write code to serialize and deserialize a given binary tree.

💡Strategies for Solving This Problem

The Encoding Challenge

This showed up at Amazon in 2024. It's about choosing the right serialization format and handling null nodes correctly.

The Problem

Convert a binary tree to a string, then reconstruct the exact tree from that string. The tree structure must be preserved perfectly, including null nodes.

Approach 1: Level Order (BFS)

Serialize level by level, using a special marker (like "null") for empty nodes.

Example tree:

    1
   / 
  2   3
     / 
    4   5

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

This is intuitive and produces compact output. Most common approach.

Approach 2: Pre-order (DFS)

Serialize using pre-order traversal (root, left, right), marking nulls.

Same tree: "1,2,null,null,3,4,null,null,5,null,null"

Longer output but easier to deserialize recursively. The null markers tell you when subtrees end.

Which to Use?

Level-order is more common and produces shorter strings. Pre-order is easier to code the deserialization recursively.

I used level-order at Amazon because it's what most people expect and it's more space-efficient.

Key Insight

You MUST encode null nodes. Without them, you can't distinguish between different tree structures that have the same values.

Example: [1,2] could be:

  1          1
 /            
2              2

With nulls: "1,2,null" vs "1,null,2"

At Amazon

Interviewer asked "Why do we need to serialize nulls?" I explained the ambiguity above. Then asked about edge cases: empty tree, single node, long chains.

Also discussed format choices - could use JSON, but string is simpler and faster.

Scroll to Top