Skip to main content

25. Serialize and Deserialize Binary Tree

hardAsked at Brex

Encode a binary tree to a string and decode it back — a design + traversal problem Brex uses to probe candidates' thinking about data persistence and approval-hierarchy snapshots.

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

Problem

Design an algorithm to serialize a binary tree to a string and deserialize that string back to the original tree structure. There is no restriction on the format you choose.

Constraints

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

Examples

Example 1

Input
root = [1,2,3,null,null,4,5]
Output
Serialize then deserialize yields the same tree

Example 2

Input
root = []
Output
[]

Approaches

1. BFS level-order serialization

Use a queue to serialize level by level with null markers; deserialize by splitting on comma and rebuilding with a queue of parent nodes.

Time
O(n)
Space
O(n)
// serialize: BFS queue, push node.val or 'null', join with ','
// deserialize: split string, BFS queue assigns left/right children in order

Tradeoff:

2. DFS preorder with null markers

Preorder DFS encodes each node value followed by '#' for null children. Deserialization consumes tokens left-to-right, recursively constructing left then right subtrees.

Time
O(n)
Space
O(n)
const serialize = (root) => {
  if (!root) return '#';
  return root.val + ',' + serialize(root.left) + ',' + serialize(root.right);
};
const deserialize = (data) => {
  const tokens = data.split(',');
  let idx = 0;
  const build = () => {
    if (tokens[idx] === '#') { idx++; return null; }
    const node = new TreeNode(+tokens[idx++]);
    node.left = build();
    node.right = build();
    return node;
  };
  return build();
};

Tradeoff:

Brex-specific tips

Brex asks about fintech infrastructure, multi-currency handling, and spend management algorithms. Expect LeetCode-style DSA focused on hash maps, sorting, and dynamic programming.

Solve it now

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

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →