Serialize and Deserialize Binary Tree

Hard

Topics
StringTreeDFSBFSDesignBinary Tree

Serialization turns a tree into a string; deserialization turns that string back into a tree. Design the pair so that deserializing a serialized tree reproduces it exactly.

You may choose any string format you like. The only requirement is that the round trip is lossless — the rebuilt tree must have the same shape and the same values, including which children are missing.

LeetCode poses this as a Codec class with two methods. The judge here calls one function that serializes its argument and immediately deserializes the result, returning the rebuilt tree, and then compares that tree against the original. Your format is never inspected, only the round trip.

Example 1

tree21435
one line123nullnull45
a nodeno child here
The lower row is the same tree written out as one flat sequence, top row first and left to right inside a row. The null tokens are not padding — they are what says "no child here", and without them a parent with only a left child would read identically to one with only a right child. Whatever is produced has to rebuild exactly this tree when read back, so the two directions are judged together.
Node values can repeat, so a token sequence cannot be checked by value alone — shape has to survive too.
Input:  root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Explanation: The rebuilt tree equals the original, which is the whole requirement.

Example 2

tree
empty tree
one line
empty string
The tree can be empty, and that case still has to survive the round trip. Its written form carries no tokens at all, so reading an empty line back has to produce an empty tree rather than a node with a missing value.
Input:  root = []
Output: []
Explanation: An empty tree has to survive the round trip too.

Example 3

tree21
one line12
a node
This tree is completely filled, so no absent-child token is needed; a tree with a gap would have to record it.
Input:  root = [1,2]
Output: [1,2]
Explanation: A node with only a left child — the format must record that the right child is absent, or the shape is lost.

Constraints

  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

The trap is thinking that a list of values is enough. It is not: [1,2] and [1,null,2] contain the same two values and are different trees, so any format that records only the values has already lost.

What has to be recorded is the absences. Once a marker is written for every missing child, the structure is fully determined and rebuilding needs no cleverness — the string can be consumed in exactly the order it was produced.

A pre-order walk makes that especially clean. Write the value, then recurse left, then right, emitting a sentinel for each null. Reading it back, the first token is the root, and the recursion consumes exactly as many tokens as its subtree produced, so the left call naturally stops where the right one begins. No lengths or brackets are needed.

A level-order format works just as well and is what this judge prints, but note the two are different: the sentinels sit in different places, and a format is only required to round-trip through itself.

Approach

  1. To serialize: walk pre-order. At a null, append a sentinel such as #. At a node, append its value. Join the tokens with a separator that cannot appear inside a value.
  2. To deserialize: split into tokens and walk them with a cursor. Read one token; if it is the sentinel, return null. Otherwise build a node from it, then recursively build its left subtree and then its right.
  3. The cursor must be shared across the recursion rather than restarted, since each call consumes a variable number of tokens.
  4. Negative values are why the separator matters: a value can begin with -, so splitting on anything that appears inside a number corrupts the stream.

Walkthrough

root = [1,2,3,null,null,4,5]

        1
       / \
      2   3
         / \
        4   5

serialize, pre-order with # for null
   1 2 # # 3 4 # # 5 # #

deserialize, consuming left to right
   1        -> node 1, build its left
     2      -> node 2, build its left
       #    -> null
       #    -> null, so node 2 is done
     3      -> node 1 right: node 3
       4    -> node 4, then # # -> done
       5    -> node 5, then # # -> done

The nulls are what make this unambiguous: without them the
token stream 1 2 3 4 5 could rebuild several shapes.

Complexity

  • Time — O(n): each node and each null marker is written once and read once.
  • Space — O(n): the string holds one token per node plus one per absent child, and the recursion is as deep as the tree.

Common Pitfalls

  • Omitting the null markers, which makes the format ambiguous — the single most common wrong answer.
  • Restarting the token cursor inside the recursion. Each subtree consumes a different number of tokens, so the position has to be shared.
  • Splitting on a character that can appear inside a value. A tree with negative numbers breaks a format that treats - as a separator.
  • Using a sentinel that collides with a real value. "0" or "-1" are values here, not markers.
  • Assuming the rebuilt tree only has to contain the same values. Shape is part of the comparison, which is what example 3 checks.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def roundTrip(self, root):
        SENTINEL = "#"

        def serialize(node, out):
            if not node:
                out.append(SENTINEL)
                return
            out.append(str(node.val))
            serialize(node.left, out)
            serialize(node.right, out)

        tokens = []
        serialize(root, tokens)

        self._at = 0

        def build(parts):
            token = parts[self._at]
            self._at += 1
            if token == SENTINEL:
                return None
            node = TreeNode(int(token))
            node.left = build(parts)
            node.right = build(parts)
            return node

        return build(tokens)
SensAI
Beta
Tap the mic to stop voice mode