FrontendInterviews.dev

Loading problem…

26. Serialize and Deserialize Binary Tree

Hard•
Acceptance: 85.71%
•
🔓3/3 Pro unlocks today

Implement two functions:

  1. serialize - Convert a binary tree to a string
  2. deserialize - Convert a string back to a binary tree

Given a binary tree node structure, serialize it to a string format and then deserialize it back to reconstruct the original tree.

Requirements

1. Serialization

  • Convert binary tree to string representation
  • Use a format that preserves tree structure
  • Handle null nodes (missing children)
  • Use comma-separated values or similar format

2. Deserialization

  • Parse string back to binary tree
  • Reconstruct exact same tree structure
  • Handle null nodes correctly
  • Maintain node values and relationships

Example Usage

// Tree structure:
//     1
//    / \
//   2   3
//      / \
//     4   5

const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(5);

const serialized = serialize(root);
// "1,2,null,null,3,4,null,null,5,null,null"

const deserialized = deserialize(serialized);
// Reconstructs the original tree

Real-World Context

This problem models real data serialization scenarios:

  • Data storage: Save tree structures to databases or files
  • Network transmission: Send tree data over APIs
  • Caching: Store tree structures for later reconstruction
  • State management: Serialize application state trees

Constraints

  • Tree nodes have val, left, right properties
  • Node values are integers
  • Handle null nodes in serialization
  • Reconstruct exact same tree structure
  • Use efficient serialization format