Serialize and Deserialize Binary Tree solution explained

To serialize a binary tree, write its values in preorder and put a marker such as # wherever a child is missing; to deserialize, read the tokens back in the same order, creating a node for each value and an empty child for each marker. Because the markers record the shape, one traversal is enough even when values repeat, and both directions take O(n) time and space.

By Published 7 min read

The problem, in plain terms

Write two functions. The first takes the root of a binary tree and returns a string. The second takes that string and returns a tree with exactly the same shape and values. You choose the format. The only requirement is that decoding what you encoded gives back the original tree, for every tree, including the empty one.

        5
       / \
    -12   30
          / \
         8   144

preorder with markers:    5,-12,#,#,30,8,#,#,144,#,#
level order with markers: 5,-12,30,#,#,8,144
An example tree and two encodings of it, made up for this page

Agree on details before writing code: can values be negative or multi-digit (yes, so a separator is needed), can they repeat, how large can the tree get, and does the string need to be human-readable or just compact?

How the problem is used in interviews

It is a design question wearing a tree costume. Interviewers want to hear why a bare list of values is ambiguous, how you encode the shape, and how your decoder knows when a subtree ends. It also checks parsing hygiene: separators, negative numbers, and the empty tree. Senior candidates are often asked about size (could the format be smaller?) and robustness (what if the input is malformed?).

A slower starting idea

One familiar approach stores the tree like a heap in an array: the root at index 0 and the children of index i at 2i + 1 and 2i + 2, with gaps for missing nodes. It decodes easily, but the array has to be as long as a complete tree of the same height. A chain of 30 nodes leaning right needs over a billion slots. Another idea is to send both the preorder and inorder lists and rebuild from them, which works only if every value is distinct and doubles the output. Both are worth mentioning to show why markers win.

The optimal approach: preorder with null markers

Pattern: tree traversal with sentinel markers. Visit nodes in preorder. For a node, write its value; for a missing child, write #. The decoder reads tokens in the same order. Each value becomes a node whose left subtree is built from the tokens that follow, then its right subtree; each # ends a branch. Because every node is followed by exactly two child slots, the decoder always knows where each subtree stops, with no need for lengths or brackets.

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

EMPTY = "#"

def serialize(root):
    out, stack = [], [root]
    while stack:                       # preorder: node, left, right
        node = stack.pop()
        if node is None:
            out.append(EMPTY)
            continue
        out.append(str(node.val))
        stack.append(node.right)       # pushed first, so handled after left
        stack.append(node.left)
    return ",".join(out)

def deserialize(data):
    tokens = data.split(",")
    if tokens[0] == EMPTY:
        return None
    root = Node(int(tokens[0]))
    stack = [[root, 0]]                # [node, how many children filled]
    for tok in tokens[1:]:
        child = None if tok == EMPTY else Node(int(tok))
        parent = stack[-1]
        if parent[1] == 0:
            parent[0].left = child
        else:
            parent[0].right = child
        parent[1] += 1
        if parent[1] == 2:
            stack.pop()                # both children placed
        if child is not None:
            stack.append([child, 0])   # its subtree comes next in preorder
    return root
Python: both directions use an explicit stack, so a 200,000-node chain is fine.

The decoder keeps a stack of nodes that still have an open child slot. Each token fills the next open slot on the top node. When a node's second slot is filled it is done and leaves the stack, and a newly created node goes on top because preorder lists its children next. The empty tree encodes as a single #, and a lone node as 42,#,#.

A recursive version is shorter and fine to write first: serialize is value, then serialize(left), then serialize(right); deserialize pulls the next token, returns None on #, otherwise builds left then right. Mention that it recurses once per level, which is why the stack version exists.

Alternative: level order with markers

Breadth-first order writes the tree row by row, which is how many coding sites display trees. Each real node contributes two child tokens, and trailing # tokens can be dropped since the decoder treats missing tokens as empty. A queue drives both directions.

function serialize(root) {
  const out = [];
  const queue = [root];
  for (let head = 0; head < queue.length; head++) {
    const node = queue[head];
    if (node === null) {
      out.push("#");
      continue;
    }
    out.push(String(node.val));
    queue.push(node.left, node.right);
  }
  while (out.length > 0 && out[out.length - 1] === "#") out.pop(); // trim tail
  return out.join(",");
}

function deserialize(data) {
  if (data === "") return null;
  const tokens = data.split(",");
  const make = (t) => (t === undefined || t === "#" ? null : { val: Number(t), left: null, right: null });
  const root = make(tokens[0]);
  const queue = [root];
  let next = 1;
  for (let head = 0; head < queue.length && next < tokens.length; head++) {
    const node = queue[head];
    node.left = make(tokens[next++]);
    node.right = make(tokens[next++]);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  return root;
}
JavaScript: level-order codec with a queue. An empty tree becomes the empty string.

The queue uses a moving head index instead of shift(), which would make each removal linear and the whole pass quadratic on large trees.

Complexity summary

n nodes, tree height h; output has about 2n + 1 tokens
ApproachTimeExtra space
Heap-style array with gapsO(2^h)O(2^h), huge for tall trees
Preorder plus inorder listsO(n) with an index mapO(n), needs distinct values
Preorder with markers, stackO(n) both waysO(h) stack plus O(n) output
Level order with markers, queueO(n) both waysO(width) queue plus O(n) output
n nodes, tree height h; output has about 2n + 1 tokens. Scroll sideways on a small screen.

Edge cases to try

  • The empty tree, in both directions.
  • A single node.
  • Negative and multi-digit values, which break any format that splits on characters instead of a separator.
  • Repeated values, which preorder with markers handles without trouble.
  • A very deep chain to the left or right, to prove nothing recurses per level.

Pitfalls

  • Leaving out null markers, so different shapes produce the same string.
  • Concatenating digits without a separator, so 1 followed by 23 reads the same as 12 followed by 3.
  • Using string concatenation in a loop in a language where that copies the whole string each time.
  • Calling shift() on a JavaScript array used as a queue in a large tree.
  • Forgetting that the decoder must consume tokens in exactly the order the encoder wrote them.

How to explain it out loud

Fictional example

Making the case for markers
Candidate
A list of values alone is ambiguous: 1,2 could be 2 as a left child or as a right child. So I'll write a marker for every missing child. With markers, preorder by itself pins down the shape.
Candidate
Decoding mirrors encoding: each value is a node, then I fill its left slot, then its right slot, from the following tokens. A marker closes a slot. I'll use stacks so a deep tree can't overflow.
Candidate
Both directions touch each node once, so O(n). If size mattered I'd talk about binary encodings or dropping trailing markers, but this format is simple to debug.

If you only had two marker-free traversals, you would need distinct values and the approach in Construct Binary Tree from Preorder and Inorder. A handy way to test Binary Tree Maximum Path Sum is to write trees in this format. For another structure you design from scratch with a clear interface, try Implement Trie.

Practice support from Natively

Design-flavored coding questions are as much about the conversation as the code. In mock rounds on Mac or Windows, Natively can read the problem from a screenshot, suggest a format and the edge cases worth testing, and transcribe your explanation so you can review whether you justified the markers clearly. Details on the AI interview assistant.

Questions people ask

How do you serialize and deserialize a binary tree?

Write the values in preorder with a marker such as # for every missing child, separated by commas. To rebuild, read the tokens in the same order: each value becomes a node whose left and then right subtrees come from the following tokens, and each marker is an empty child.

Why do you need null markers?

Without them, different tree shapes can produce the same list of values. The markers record where each branch ends, so a single traversal is enough to rebuild the exact tree.

What is the time complexity of serializing a binary tree?

O(n) time in both directions, and O(n) space for the output string, which holds about 2n + 1 tokens.

Is preorder or level order better for serialization?

Both work in O(n). Preorder pairs naturally with a stack or recursion; level order matches how many coding sites display trees. Use explicit stacks or queues for very deep trees.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP