Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Serialize and Deserialize Binary Tree

HardPython00:00
I
Practice interviewer
Your interviewer
In session
I
Interviewer

Welcome to the Python screen.

The question is on your right: Serialize and Deserialize Binary Tree. Read through the requirements first.

Run and submit your code as often as you need. You also have five interviewer messages this session - want to talk through your approach, or are you ready to start coding?

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