Serialize and Deserialize Binary Tree

Design an algorithm to serialize and deserialize a binary tree.

Pattern

Pre-order + Null Markers

This problem follows the Pre-order + Null Markers pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Pre-order traversal with null markers. Deserialize by consuming tokens in order.

Key Insight

Pre-order + null markers uniquely define a tree — the null markers tell you exactly when to stop recursing and return up.

Step-by-step

  1. 1Serialize: pre-order traversal, use a marker (e.g. '#') for null nodes
  2. 2Deserialize: consume tokens in pre-order, recursively build left then right
  3. 3Use an iterator/index to track position in the token stream

Pseudocode

def serialize(root):
    if not root: return '#'
    return str(root.val) + ',' + serialize(root.left) + ',' + serialize(root.right)

def deserialize(data):
    tokens = iter(data.split(','))
    def build():
        val = next(tokens)
        if val == '#': return null
        node = TreeNode(int(val))
        node.left = build()
        node.right = build()
        return node
    return build()
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Trees Problems

Master this pattern with YeetCode

Practice Serialize and Deserialize Binary Tree and similar Trees problems with flashcards. Build pattern recognition through active recall.

Practice this problem