Skip to main content

297. Serialize and Deserialize Binary Tree

hardAsked at LinkedIn

Design an algorithm that serializes a binary tree to a string and back. LinkedIn asks this on senior loops because the preorder-with-nulls + queue-based recursive parse is the cleanest pair you can write under interview pressure.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Source citations

Public interview reports confirming this problem appears in LinkedIn loops.

  • Glassdoor (2026-Q1)LinkedIn senior IC onsite reports list this as the canonical design + recursion problem.
  • Blind (2025-12)LinkedIn writeups specifically mention the preorder-with-nulls scheme as the expected encoding.

Problem

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -1000 <= Node.val <= 1000

Examples

Example 1

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

Example 2

Input
root = []
Output
[]

Approaches

1. Preorder DFS with nulls + comma delimiter (optimal)

Serialize: preorder DFS, emit node.val for real nodes and '#' for null, comma-separated. Deserialize: tokenize on commas, then a recursive consumer eats tokens in the same preorder.

Time
O(n) both directions
Space
O(n) for string + recursion
function serialize(root) {
  const parts = [];
  function dfs(node) {
    if (!node) { parts.push('#'); return; }
    parts.push(String(node.val));
    dfs(node.left);
    dfs(node.right);
  }
  dfs(root);
  return parts.join(',');
}
function deserialize(data) {
  const tokens = data.split(',');
  let i = 0;
  function build() {
    const t = tokens[i++];
    if (t === '#') return null;
    const node = new TreeNode(parseInt(t, 10));
    node.left = build();
    node.right = build();
    return node;
  }
  return build();
}

Tradeoff: Cleanest pair. Preorder naturally aligns with the recursive parse — each `build()` call consumes exactly one subtree's tokens. The '#' for null is the standard sentinel.

2. BFS with nulls (level-order serialization)

Serialize level by level using a queue, pushing '#' for null children. Deserialize: parse the top-level then walk the queue to assign children from the next tokens.

Time
O(n) both directions
Space
O(n)
function serializeBFS(root) {
  if (!root) return '';
  const parts = [];
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    if (!node) { parts.push('#'); continue; }
    parts.push(String(node.val));
    queue.push(node.left);
    queue.push(node.right);
  }
  return parts.join(',');
}
function deserializeBFS(data) {
  if (!data) return null;
  const tokens = data.split(',');
  const root = new TreeNode(parseInt(tokens[0], 10));
  const queue = [root];
  let i = 1;
  while (queue.length) {
    const node = queue.shift();
    if (tokens[i] !== '#') {
      node.left = new TreeNode(parseInt(tokens[i], 10));
      queue.push(node.left);
    }
    i++;
    if (tokens[i] !== '#') {
      node.right = new TreeNode(parseInt(tokens[i], 10));
      queue.push(node.right);
    }
    i++;
  }
  return root;
}

Tradeoff: Matches LC's `[1,2,3,null,null,4,5]` notation more literally. Slightly harder to write under pressure than preorder; preorder is the LinkedIn-preferred answer.

LinkedIn-specific tips

LinkedIn interviewers want the preorder + '#' scheme by default. Articulate the symmetry: 'Serialization is a preorder DFS that emits '#' for null. Deserialization is the inverse — a recursive consumer that calls itself twice per node (left then right) and stops on '#'.' If they push for BFS, fine — but preorder is shorter and easier to debug.

Common mistakes

  • Using inorder or postorder — inorder is ambiguous (two different trees can have the same inorder), postorder works but the right-first traversal is unintuitive.
  • Forgetting the '#' for null — leads to ambiguity when reconstructing.
  • In deserialize, using a global counter without resetting it — breaks if serialize/deserialize are called multiple times on the same object.

Follow-up questions

An interviewer at LinkedIn may pivot to one of these next:

  • Serialize and Deserialize BST (LC 449) — no need for null sentinels because BST values constrain structure.
  • Serialize and Deserialize N-ary Tree (LC 428) — different node structure.
  • Could you do this in O(n) space without recursion? (Iterative with an explicit stack.)

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

FAQ

Why preorder and not inorder?

Inorder of a tree is ambiguous — two structurally different trees can produce the same inorder. Preorder (or postorder) uniquely identifies a tree when combined with null sentinels.

Why is '#' the standard null sentinel?

Because it's a single character that can't appear in integer tokens, so the comma-delimited parser handles it without special escaping. You could use any non-digit string ('null', 'X', etc.); '#' is convention.

Free learning resources

Curated free links for this problem.

Practice these live with InterviewChamp.AI

Drill Serialize and Deserialize Binary Tree and other LinkedIn interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →