Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Serialize and Deserialize Binary Tree

HardPython00:00
I
Practice interviewer
In session
5 left
00:00

Your question is Serialize and Deserialize Binary Tree. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

In a Meta-style systems setting such as caching tree-structured ranking features for Facebook Feed, you may need to convert a binary tree into a compact string and later rebuild the exact same tree. Implement both serialization and deserialization.

Given the root of a binary tree, write two functions:

  1. serialize(root) that converts the tree into a string.
  2. deserialize(data) that reconstructs the original binary tree from that string.

Your encoding must preserve both node values and structure, including missing children.

Formal Specification

  • Input to serialize: root, the root node of a binary tree or null
  • Output from serialize: a string representation of the tree
  • Input to deserialize: data, a string produced by serialize
  • Output from deserialize: the reconstructed root node or null

You may choose any deterministic format, but deserialize(serialize(root)) must produce a tree identical to the original.

Constraints

  • The number of nodes is in the range [0, 10^4]
  • -1000 <= Node.val <= 1000
  • The tree may be empty
  • The tree may be highly unbalanced
  • deserialize must correctly reconstruct any string produced by serialize

Function Signature

def serialize_deserialize_tree(root):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output