Skip to main content

297. Serialize and Deserialize Binary Tree

hardAsked at Pinterest

Pinterest stores trees-shaped data — board hierarchies, comment threads — in caches and databases that need a string representation. Serialize and Deserialize Binary Tree asks you to convert a tree to a string and back while preserving structure. The interviewer wants either preorder DFS or BFS with null markers.

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

Source citations

Public interview reports confirming this problem appears in Pinterest loops.

  • Glassdoor (2026-Q1)Pinterest L4/L5 onsite reports cite Serialize/Deserialize as a hard tree round.
  • LeetCode Pinterest tag (2026-Q1)On the Pinterest company-tagged problem list, often pairs with LRU Cache as a design round.

Problem

Design an algorithm to serialize and deserialize a binary tree. 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 in the same or another computer environment. There is no restriction on how your serialization/deserialization algorithm should work — but the deserialized tree must equal the original.

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]

Explanation: Round-trip should be identity.

Example 2

Input
root = []
Output
[]

Approaches

1. Preorder DFS with null markers (optimal)

Serialize: preorder walk, append val for nodes and a sentinel ('#') for null children, comma-separated. Deserialize: split on comma, consume tokens in preorder recursive build.

Time
O(n) both directions
Space
O(n)
function serialize(root) {
  const out = [];
  function dfs(node) {
    if (!node) { out.push('#'); return; }
    out.push(String(node.val));
    dfs(node.left);
    dfs(node.right);
  }
  dfs(root);
  return out.join(',');
}

function deserialize(data) {
  const tokens = data.split(',');
  let i = 0;
  function build() {
    const t = tokens[i++];
    if (t === '#') return null;
    const node = { val: parseInt(t, 10), left: null, right: null };
    node.left = build();
    node.right = build();
    return node;
  }
  return build();
}

Tradeoff: Cleanest implementation. Preorder + null markers is the canonical answer because it uniquely identifies a tree (unlike inorder alone, which is ambiguous). Mention this uniqueness when narrating.

2. BFS level-by-level with null markers

Serialize: BFS, emit val or '#'. Deserialize: iterate tokens; for each non-null parent, pair it with the next two tokens as children.

Time
O(n) both directions
Space
O(n)
function serializeBfs(root) {
  if (!root) return '';
  const out = [];
  const q = [root];
  while (q.length) {
    const node = q.shift();
    if (!node) { out.push('#'); continue; }
    out.push(String(node.val));
    q.push(node.left);
    q.push(node.right);
  }
  return out.join(',');
}

function deserializeBfs(data) {
  if (!data) return null;
  const tokens = data.split(',');
  const root = { val: parseInt(tokens[0], 10), left: null, right: null };
  const q = [root];
  let i = 1;
  while (q.length && i < tokens.length) {
    const node = q.shift();
    const lt = tokens[i++];
    if (lt !== '#') {
      node.left = { val: parseInt(lt, 10), left: null, right: null };
      q.push(node.left);
    }
    const rt = tokens[i++];
    if (rt !== '#') {
      node.right = { val: parseInt(rt, 10), left: null, right: null };
      q.push(node.right);
    }
  }
  return root;
}

Tradeoff: Matches the LeetCode display format more naturally. No recursion-depth risk on skewed trees. Slightly more bookkeeping than the DFS version.

Pinterest-specific tips

Pinterest interviewers grade three things: (1) you pick a format that round-trips uniquely (preorder with null markers is the canonical choice); (2) the serialize and deserialize are inverses — verify on the example out loud; (3) you handle the all-null root case (empty string or just '#'). Volunteer 'this format is bigger than the minimum representation; if compactness mattered I'd use a balanced BST and skip the markers' — that's the senior follow-up bait.

Common mistakes

  • Using inorder traversal alone — that's ambiguous (multiple trees produce the same inorder).
  • Forgetting null markers — without them, you can't distinguish 'left child is X' from 'no left child, right child is X'.
  • Returning the deserialized tree as an array instead of a TreeNode object.
  • Mutating a shared i index across multiple deserialize calls without re-initializing.

Follow-up questions

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

  • Encode and Decode Strings (LeetCode 271) — same primitive, list of strings instead of a tree.
  • Serialize a BST more compactly (LeetCode 449) — no null markers needed because BST property reconstructs structure.
  • N-ary tree (LeetCode 428): how does the format change?
  • Streaming: serialize an evolving tree — emit a diff, not the full re-encoding.

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 is preorder uniquely identifying but inorder isn't?

Inorder lists values in sorted-by-position order without revealing structure; multiple trees can have the same inorder. Preorder commits to 'root first', so the first token of every subtree is its root, allowing recursive reconstruction.

What's the smallest possible representation?

For balanced BSTs, you can omit null markers entirely (LeetCode 449). For general binary trees you need the markers OR pair preorder+inorder, both of which take O(n) chars.

Free learning resources

Curated free links for this problem.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →