Serialize and Deserialize Binary Tree

Free with account Updated Nov 19, 2026 · 6 min read
On this page

    Problem statement

    Design two functions for a binary tree: serialize turns a tree into a string, and deserialize turns that string back into a tree with exactly the same shape and values. You choose the string format. Node values are integers and may be negative. The tree can be empty.

    This question tests design as much as code: you pick the format, explain why it is unambiguous, and then write two functions that agree with each other. Original problem: LeetCode 297.

    Example

    The tree 1, 2, 3, 4, 5 becomes the string "1,2,#,#,3,4,#,#,5,#,#", and reading the string back produces the same tree.
    The tree 1, 2, 3, 4, 5 becomes the string "1,2,#,#,3,4,#,#,5,#,#", and reading the string back produces the same tree.
    Input:  root = [1, 2, 3, null, null, 4, 5]
    serialize(root)                -> "1,2,#,#,3,4,#,#,5,#,#"
    deserialize("1,2,#,#,3,4,#,#,5,#,#") -> the same tree
    Input:  root = []
    serialize(root) -> "#"
    deserialize("#") -> null

    Constraints (assumed)

    • 0 ≤ number of nodes ≤ 10,000.
    • −1,000 ≤ node value ≤ 1,000.

    What this question tests

    • Seeing that a traversal order alone is not enough to recover a tree's shape, and knowing what fixes it (null markers, or two traversals).
    • Writing two functions that use the same order, so the reader consumes exactly what the writer produced.
    • Thinking about the format: separators, negative numbers, size, and the empty tree.

    Questions to ask first

    1. Can values be negative or have several digits? (Yes, so use a separator and don't rely on one character per value.)
    2. Is it a binary search tree? For a BST, pre-order without null markers is enough, because the values tell you where each node goes.
    3. Does the string need to be compact or human-readable? This decides between text and a binary format.
    4. Can there be duplicate values? (Yes. That rules out the "pre-order plus in-order" approach, which needs unique values.)