Serialize and Deserialize Binary Tree
Master this topic with zero to advance depth.
Serialize and Deserialize Binary Tree
Tree to string and back.
Level I: BFS (Level Order)
Intuition
Standard level-order traversal (BFS) using a queue allows us to convert the tree into a list of strings. Empty children are represented as '#'.
Thought Process
- Use a queue to traverse the tree level by level.
- For each node, append its value to the result string.
- If a child is null, append '#' instead.
- When deserializing, split by ',' and use a queue to reconstruct parent-child links.
Detailed Dry Run
| Tree | Serialized String |
|---|---|
| [1, 2, 3] | "1,2,3,#,#,#,#" |
| [1, null, 2] | "1,#,2,#,#" |
Level II: Postorder DFS
Intuition
Postorder traversal (Left, Right, Root) is also a valid way to serialize. Deserialization starts from the end of the list and builds the root first, then the right child, then the left child.
Logic
- Serialize:
dfs(left),dfs(right),append(val). - Deserialize: Pop from end of list, read
val, thenroot.right = dfs(),root.left = dfs().
Detailed Dry Run
Serialize [1, 2, 3] -> [#, #, 2, #, #, 3, 1]. Pop 1 (root), then 3 (right), then 2 (left).
Level III: Optimal (Preorder DFS)
Intuition
Thought Process
Preorder DFS (Root, Left, Right) is more compact and easier to code recursively. We use a List or a String Join for serialization. During deserialization, we convert the string back into a Queue or use an index, then recursively rebuild the structure.
Patterns
DFS Preorder Serialization: Maintain structure by marking leaves explicitly.
Complexity
- Time:
- Space:
Detailed Dry Run
| Node | Action | Serialized |
|---|---|---|
| 1 | Visit | [1] |
| 2 | Visit | [1, 2] |
| null | Visit | [1, 2, #] |
| null | Visit | [1, 2, #, #] |
⚠️ Common Pitfalls & Tips
Be aware of recursion limits for very large trees. Serialization strings can become very large, so StringBuilder (Java) or join (Python) is much faster than string concatenation.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.