PPractick

DSA interview question

Serialize and Deserialize a Binary Tree

Hard · Data structures · Topics: tree, design, string

The problem

A distributed cache must store binary trees as strings and later rebuild them exactly, including their shape. Preorder with an explicit marker for missing children does it compactly: write the node's value, then serialise its left subtree, then its right subtree, and write # for every null. Because every null is recorded, the string encodes the shape unambiguously, and deserialisation just reads the tokens back in the same preorder.

Example: [1, 2, 3, null, null, 4, 5] → "1,2,#,#,3,4,#,#,5,#,#" → the same tree.

Function signature

class Codec {
public:
    string serialize(TreeNode* root);
    TreeNode* deserialize(const string& data);
};

Test cases

Input (level order)SerializedRebuilt (level order)
[1, 2, 3, null, null, 4, 5]"1,2,#,#,3,4,#,#,5,#,#"[1, 2, 3, null, null, 4, 5]
[]"#"[]
[1]"1,#,#"[1]
[-5, 10]"-5,10,#,#,#"[-5, 10]
[1, null, 2, null, 3]"1,#,2,#,3,#,#"[1, null, 2, null, 3]

(Confirm: values can be negative or repeated; the format is free as long as deserialize(serialize(t)) rebuilds t exactly.)

How interviewers phrase it

Clarifying questions to ask

  1. Any format constraints? (No: any self-consistent format.)
  2. Can values be negative or repeated? (Yes, so separators are needed and values can't identify nodes.)
  3. Is the size of the string important? (It's O(n) either way.)

Follow-ups to expect

  1. "Why record nulls?"
  2. "Why does deserialisation work with one pointer?"
  3. "Level-order format instead?"
  4. "What about BSTs?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in