Skip to content
Preptima
mediumCodingMidSeniorStaff

Serialise a binary tree to a string and reconstruct exactly the same tree from it. What has to be in the string?

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

A bare traversal is not enough, because two different trees can produce identical node sequences. Emitting an explicit marker for every absent child makes a preorder walk unambiguous, and reading it back is the same walk consuming tokens in the same order from a single cursor.

Keep binary trees explicit in the answer because that is the concept the interviewer is actually trying to test. A good binary trees explanation names the trade-off, the failure mode, and the evidence you would use before choosing. Use binary trees once more at the decision point so the answer reads as judgement rather than a detached example.

Keep binary trees explicit in the answer because that is the concept the interviewer is actually trying to test. A good binary trees explanation names the trade-off, the failure mode, and the evidence you would use before choosing.

Was this answer helpful?

Likely follow-ups

  • Do it iteratively, with no recursion in either direction.
  • The values are arbitrary strings that may contain your delimiter. What changes?
  • Serialise a binary search tree specifically. Can you use fewer bytes than this, and how?
  • Two clients disagree about the format version. How would you make the encoding self-describing without breaking existing data?

Related questions