Serialize and Deserialize Binary Tree
On this page
Problem statement
Design two functions for a binary tree:
serializeturns a tree into a string, anddeserializeturns that string back into a tree with exactly the same shape and values. You choose the string format. Node values are integers and may be negative. The tree can be empty.
This question tests design as much as code: you pick the format, explain why it is unambiguous, and then write two functions that agree with each other. Original problem: LeetCode 297.
Example

Input: root = [1, 2, 3, null, null, 4, 5]
serialize(root) -> "1,2,#,#,3,4,#,#,5,#,#"
deserialize("1,2,#,#,3,4,#,#,5,#,#") -> the same tree
Input: root = []
serialize(root) -> "#"
deserialize("#") -> null
Constraints (assumed)
- 0 ≤ number of nodes ≤ 10,000.
- −1,000 ≤ node value ≤ 1,000.
What this question tests
- Seeing that a traversal order alone is not enough to recover a tree's shape, and knowing what fixes it (null markers, or two traversals).
- Writing two functions that use the same order, so the reader consumes exactly what the writer produced.
- Thinking about the format: separators, negative numbers, size, and the empty tree.
Questions to ask first
- Can values be negative or have several digits? (Yes, so use a separator and don't rely on one character per value.)
- Is it a binary search tree? For a BST, pre-order without null markers is enough, because the values tell you where each node goes.
- Does the string need to be compact or human-readable? This decides between text and a binary format.
- Can there be duplicate values? (Yes. That rules out the "pre-order plus in-order" approach, which needs unique values.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.