Serialize and Deserialize Binary Tree
Encode a binary tree to a string and decode it back exactly.
Open on LeetCode ↗Intuition
Preorder with explicit null markers is unambiguous: the nulls pin down where subtrees end, so the same recursion that wrote the string can replay it. Serialization is a preorder dump; deserialization is the mirror-image recursive read.
Approach
Serialize: preorder + '#' for null
dfs(node): emit val, recurse left, recurse right; emit # at nulls. Join with commas (handles multi-digit and negatives).
Deserialize: consume in the same order
Read the next token: '#' → None; else make the node and build left then right. An iterator carries the position implicitly.
Why it round-trips
Preorder with nulls encodes the exact shape — no inorder needed, unlike the classic two-traversal reconstruction.
Solution & live demo
Edge cases
Serializes to "#" and decodes to None.
Comma delimiting keeps tokens intact — never parse per character.