The Problem

Design an algorithm to serialize and deserialize a binary tree. Serialization is the process of converting a tree to a string. Deserialization is reconstructing the tree from that string.

There is no restriction on how your serialization/deserialization algorithm should work โ€” you just need to ensure that a binary tree can be serialized to a string and that this string can be deserialized back to the original tree structure.

Example: The tree [1,2,3,null,null,4,5] serializes to "1,2,null,null,3,4,null,null,5,null,null" using preorder DFS with null markers.

Interactive Visualization

Speed:
Binary Tree
Serialized String
Press Step or Play to begin.
Code

                
Current Step
Press Step or Play to begin.

How It Works

Key Insight

Preorder traversal (root, left, right) with null markers uniquely identifies a binary tree. By recording "null" for every missing child, we capture the full structure โ€” not just the values. During deserialization, we consume tokens in the exact same preorder sequence, using "null" tokens to know when a subtree is empty and we should backtrack.

Serialize Algorithm

  • Perform a preorder DFS (visit root, then left subtree, then right subtree).
  • At each node, append the node's value to the result list.
  • When you reach a null child, append the string "null".
  • Join all tokens with commas to produce the final string.

Deserialize Algorithm

  • Split the serialized string by commas to get a list of tokens.
  • Maintain a pointer i that tracks which token to consume next.
  • Recursively build the tree in preorder: consume a token, create a node (or return null), then recurse for left and right children.
  • The pointer ensures each token is consumed exactly once in the correct order.

Complexity

Time O(n)
Space O(n)

Both serialization and deserialization visit each node exactly once. The serialized string and the reconstructed tree each use O(n) space, where n is the number of nodes. The recursion stack uses O(h) space where h is the height of the tree (O(n) in the worst case for a skewed tree).