Learning on Web Dev Open is free for all.

Interview Prep · CodeSerialize and deserialize a binary tree
← Code

Serialize and deserialize a binary tree

Medium30 minFree, no account

Any traversal will serialize it. Only some of them can rebuild it.


The question

Write serialize(root) to a string and deserialize(str) back to the identical tree.

The tree is not a search tree and values are arbitrary integers including negatives.

    1
   / \
  2   3
     / \
    4   5

deserialize(serialize(root))  // structurally identical
30:00Commit to an answer before you open the solution. Reading it first teaches you to recognise good answers, which is not the skill being tested.

Stuck?

0 of 3 hints taken

The worked solution

written by a person · not a grade

Score yourself

0 of 5 marked
  • Chose a traversal that is actually reversible and said why25
  • Encoded nulls to capture shape25
  • Deserialization consumes from a shared cursor correctly25
  • Delimiter handles negatives and multi-digit values15
  • Stated complexity and the recursion-depth risk10

We run no AI here and nothing on this page grades you. The score is yours, and the useful number is the one you get on the same problem a month from now, cold.

kept in this browser only