DSA interview question
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.
class Codec {
public:
string serialize(TreeNode* root);
TreeNode* deserialize(const string& data);
};
| Input (level order) | Serialized | Rebuilt (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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in