← Back to Algorithms, page 3

algorithms-0057 · Hard senior

Serialize and deserialize a binary tree: convert a tree to a string and rebuild exactly the same shape and values from that string.

Write a preorder traversal with a marker such as '#' for every missing child; the markers make the shape unambiguous. To rebuild, read tokens in the same order with an iterator: a number creates a node and then builds its left and right subtrees, '#' returns None. Both directions are O(n). A level-order format with trailing markers trimmed is the common alternative.

Full answer

Problem

Design serialize(root) -> str and deserialize(s) -> root so that deserialize(serialize(t)) produces a tree with the same structure and values as t.

Example: the tree 1 -> 2, (3 -> 4, 5) can be written as "1,2,#,#,3,4,#,#,5,#,#" in preorder, or "1,2,3,#,#,4,5" in level order.

Constraints: up to 10^4 nodes, values from -1000 to 1000. The format is yours to choose but must be lossless.

Brute force

Store both preorder and inorder sequences and rebuild using the classic two-traversal construction. It works only when values are unique, needs two passes and a hash map, and doubles the output size.

Optimal approach

Preorder with null markers:

  • serialize: visit node, write its value, recurse left, recurse right; write # for None.
  • deserialize: split on commas, wrap in an iterator, and define build(): take the next token; if # return None; otherwise create a node, then set left = build() and right = build().

Level-order variant: BFS writing # for None children, then trim trailing #. Rebuild with a queue, attaching the next two tokens as left and right of each dequeued node.

Why it works

With explicit null markers, every subtree's encoding is self-delimiting: a subtree is either # or a value followed by two complete subtree encodings. That grammar has exactly one parse, so the decoder consumes the same tokens in the same order and rebuilds the same shape. Duplicates are fine because no value lookups are needed.

Complexity

O(n) time each way. Output length is O(n): n values plus n + 1 markers. The recursion depth is O(h); an explicit stack or the BFS version avoids recursion limits on deep chains.

Code

python
import random
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def serialize(root):
    """Preorder with '#' for missing children. O(n) time and output size."""
    out = []

    def walk(node):
        if node is None:
            out.append("#")
            return
        out.append(str(node.val))
        walk(node.left)
        walk(node.right)
    walk(root)
    return ",".join(out)


def deserialize(data):
    tokens = iter(data.split(","))

    def build():
        tok = next(tokens)
        if tok == "#":
            return None
        node = TreeNode(int(tok))
        node.left = build()
        node.right = build()
        return node
    return build()


def serialize_bfs(root):
    """Level order variant (the format many judges print). Trailing '#' trimmed."""
    out, q = [], deque([root])
    while q:
        node = q.popleft()
        if node is None:
            out.append("#")
            continue
        out.append(str(node.val))
        q.append(node.left)
        q.append(node.right)
    while out and out[-1] == "#":
        out.pop()
    return ",".join(out)


def deserialize_bfs(data):
    if not data:
        return None
    toks = data.split(",")
    root = TreeNode(int(toks[0]))
    q, i = deque([root]), 1
    while q and i < len(toks):
        node = q.popleft()
        for side in ("left", "right"):
            if i < len(toks) and toks[i] != "#":
                child = TreeNode(int(toks[i]))
                setattr(node, side, child)
                q.append(child)
            i += 1
    return root


def same(a, b):
    if a is None or b is None:
        return a is b
    return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return None
    return TreeNode(rng.randint(-50, 50), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
    assert serialize(t) == "1,2,#,#,3,4,#,#,5,#,#"
    assert serialize_bfs(t) == "1,2,3,#,#,4,5"
    assert serialize(None) == "#" and deserialize("#") is None
    assert serialize_bfs(None) == "" and deserialize_bfs("") is None
    rng = random.Random(57)
    for _ in range(2000):
        r = random_tree(rng, 6)
        assert same(deserialize(serialize(r)), r)
        assert same(deserialize_bfs(serialize_bfs(r)), r)
    print("all tests passed")

Save as b57_serialize_tree.py and run python3 b57_serialize_tree.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty tree ("#" in preorder, "" in level order). Negative and multi-digit values (a delimiter is needed). Duplicate values. Very deep chains (prefer BFS or an iterative decoder).

Pattern

Self-delimiting encoding of recursive structures. The same idea underlies parsers for nested data, Merkle tree hashing of subtrees, and detecting duplicate subtrees by serializing each one.

python
import random
from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def serialize(root):
    """Preorder with '#' for missing children. O(n) time and output size."""
    out = []

    def walk(node):
        if node is None:
            out.append("#")
            return
        out.append(str(node.val))
        walk(node.left)
        walk(node.right)
    walk(root)
    return ",".join(out)


def deserialize(data):
    tokens = iter(data.split(","))

    def build():
        tok = next(tokens)
        if tok == "#":
            return None
        node = TreeNode(int(tok))
        node.left = build()
        node.right = build()
        return node
    return build()


def serialize_bfs(root):
    """Level order variant (the format many judges print). Trailing '#' trimmed."""
    out, q = [], deque([root])
    while q:
        node = q.popleft()
        if node is None:
            out.append("#")
            continue
        out.append(str(node.val))
        q.append(node.left)
        q.append(node.right)
    while out and out[-1] == "#":
        out.pop()
    return ",".join(out)


def deserialize_bfs(data):
    if not data:
        return None
    toks = data.split(",")
    root = TreeNode(int(toks[0]))
    q, i = deque([root]), 1
    while q and i < len(toks):
        node = q.popleft()
        for side in ("left", "right"):
            if i < len(toks) and toks[i] != "#":
                child = TreeNode(int(toks[i]))
                setattr(node, side, child)
                q.append(child)
            i += 1
    return root


def same(a, b):
    if a is None or b is None:
        return a is b
    return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return None
    return TreeNode(rng.randint(-50, 50), random_tree(rng, depth - 1), random_tree(rng, depth - 1))


if __name__ == "__main__":
    t = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
    assert serialize(t) == "1,2,#,#,3,4,#,#,5,#,#"
    assert serialize_bfs(t) == "1,2,3,#,#,4,5"
    assert serialize(None) == "#" and deserialize("#") is None
    assert serialize_bfs(None) == "" and deserialize_bfs("") is None
    rng = random.Random(57)
    for _ in range(2000):
        r = random_tree(rng, 6)
        assert same(deserialize(serialize(r)), r)
        assert same(deserialize_bfs(serialize_bfs(r)), r)
    print("all tests passed")

Preorder codec with an iterator-based decoder and a level-order codec; 2,000 random trees round-trip through both.

Complexity

Time: O(n). Space: O(n) output, O(h) recursion. The level-order codec uses O(w) queue space and no recursion.

By level

Fresher: Explains why null markers are needed using two different trees that would otherwise encode the same way. Writes the preorder encoder and follows the decoder on a small example.

Mid: Implements both directions with an iterator, handles empty trees and negatives, and states the O(n) cost. Compares preorder and level-order formats.

Senior: Discusses compact binary formats, versioning a stored format, and decoding untrusted input safely with depth and size limits. Uses subtree serialization to detect duplicate subtrees with hashing.

Key points

  • Null markers make the encoding unambiguous
  • Decode in exactly the same traversal order
  • An iterator over tokens keeps the decoder simple
  • Works with duplicate values
  • Output is O(n)

Common mistakes

  • Omitting null markers so different shapes produce the same string
  • Using string slicing in the decoder, causing O(n^2)
  • No delimiter, breaking multi-digit or negative values
  • Relying on unique values via preorder plus inorder

Follow-ups

  • How would you make the format more compact (binary, varints, bitmap of nulls)?
  • How do you find duplicate subtrees using serialization?
  • How would you serialize an n-ary tree?

Tips

  • State the grammar of the encoding
  • Test the empty tree and negative values
  • Mention BFS to avoid deep recursion

Evaluation rubric

  • Lossless format
  • Correct decoder
  • O(n) both ways
  • Handles empty and negative inputs