Serialize and Deserialize Binary Tree
Problem
Design a codec that converts a binary tree to a string and back. serialize(root) must produce a string, and deserialize(data) must rebuild a tree with exactly the same shape and values from that string. You may choose any format as long as the round trip is exact; you are not required to match any particular encoding. The tree may be empty.
- The tree has at most 15,000 nodes.
- Node values are integers between -1,500 and 1,500.
Examples
root = [9, 3, 20, None, None, 15, 7]→ serializing produces"9,3,20,#,#,15,7,#,#,#,#", and deserializing that string rebuilds a tree whose level-order form is[9, 3, 20, None, None, 15, 7].root = []→ serializing the empty tree gives"", and deserializing""gives backNone.root = [42]→ a single node serializes to"42,#,#"and round-trips to[42].
Hints
- Why can you not rebuild a tree from a plain preorder list of values? What is missing?
- If you write an explicit marker every time a child is absent, does one traversal become enough?
- Level-order (BFS) with a null marker per missing child, values separated by a delimiter; deserialize with the same queue discipline, consuming two tokens per real node.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.