Design an algorithm to serialize a binary tree into a string, and deserialize that string back into a tree with the exact same structure.
Example
Input root = [1,2,3,null,null,4,5]
Output "1,2,N,N,3,4,N,N,5,N,N" (format can vary by implementation)
Key Pointers
A preorder traversal (root, then left, then right) is enough to reconstruct the tree exactly, as long as missing children are explicitly recorded — without those markers the structure is ambiguous.
Serializing is a straightforward preorder DFS that writes a sentinel like "N" for a None child instead of skipping it.
Deserializing rebuilds the tree by consuming tokens in the same left-then-right order they were written, using a shared iterator both recursive calls pull from.
Step-by-Step Analysis
Serialize: DFS the tree in preorder, appending str(node.val) for a real node or "N" for a None child, joined by commas.
Deserialize: split the string back into tokens and wrap them in an iterator.
Define a recursive build() that reads the next token; if it's "N", return None.
Otherwise create a TreeNode with that value, then recursively set node.left = build() and node.right = build().
Return the reconstructed root once the whole token stream has been consumed.
serialize does a preorder DFS: write the node's value, then serialize the left subtree, then the right.
Every missing child is written as "N". Without these markers, different shapes could produce the same list of values.
deserialize reads the values back in the same order with an iterator.
A value creates a node, then build() is called for its left and then its right child; "N" returns None, which tells the recursion where each branch ends.
Both directions are O(n) time and O(n) space.
Visual Walkthrough
Running it on root = [1, 2, 3, null, null, 4, 5]:
Recording the empty children (N) makes the string describe the exact shape, so one preorder list is enough to rebuild the tree. Badges show the order in which nodes are written.