31 / 75
Hard
Serialize and Deserialize Binary Tree
#31treedfsbfsdesignstring
Convert tree to string and back using BFS level-order or DFS pre-order traversal.
Example:
Input:
root=[1,2,3,null,null,4,5]Output:
Serialized string that deserializes back to same treeCommon Mistakes:
- Not handling empty tree (null root)
- Forgetting to serialize null children (loses structure)
- Index out of bounds in deserialization
- Not choosing a delimiter that won't conflict with node values
Notes:
BFS approach shown. Can also use DFS pre-order. Time O(n) for both, Space O(n). Format: '1,2,3,null,null,4,5,'
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Convert tree to string and back using BFS level-order or DFS pre-order traversal.
Example:
Input:
root=[1,2,3,null,null,4,5]Output:
Serialized string that deserializes back to same treeCommon Mistakes:
- Not handling empty tree (null root)
- Forgetting to serialize null children (loses structure)
- Index out of bounds in deserialization
- Not choosing a delimiter that won't conflict with node values
Notes:
BFS approach shown. Can also use DFS pre-order. Time O(n) for both, Space O(n). Format: '1,2,3,null,null,4,5,'
31/75
Serialize and Deserialize Binary Tree