Skip to the solution
HardDSA11 min read

How do you serialize and deserialize a binary tree?

870 views

The problem

Question presented to candidate: "Design two Python functions: serialize, which turns a binary tree into a string, and deserialize, which turns that string back into an identical tree. The format is up to you, but the round trip must be exact for any tree."

What a strong answer should cover:

  • Why a plain traversal is not enough: different shapes can share the same preorder, so missing children must be recorded with a null marker.
  • Preorder with null markers: serialize recursively; deserialize by consuming tokens in the same order with one moving position. O(n) time and space.
  • The level-order (BFS) alternative used by LeetCode: a queue, null for gaps, trailing nulls trimmed; deserialize by reading two tokens per parent.
  • A delimiter between tokens so negative and multi-digit values parse correctly.
  • Trade-offs: string size of each format, recursion depth versus an iterative queue.
  • Python specifics: build a list and ",".join it, consume tokens with iter() + next(), use collections.deque (not list.pop(0)) for BFS, and remember recursion depth on deep trees.

Clarifying questions expected:

  • What values can nodes hold (negative numbers, very large numbers, strings)?
  • Does the format need to be human-readable or compatible with anything else?

Code / implementation expected: Yes โ€” preorder serialize / deserialize (and optionally the BFS version), in Python 3.

  • trees
  • serialization

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonPreorder with # markers: serialize, deserialize, round trip
PythonLeetCode BFS format, format sizes, and the ambiguity of no markers

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 135 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Count of smaller numbers after self with Fenwick tree โ€” how to coordinate compress?

Continue