We need to implement two methods:
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
# Convert a binary tree into a string.
pass
def deserialize(self, data: str) -> Optional[TreeNode]:
# Reconstruct the original binary tree from that string.
pass
The important clues are:
A natural solution is preorder DFS (Depth-First Search).
Preorder visits nodes in this order:
For every missing child, record a marker such as N.
A naive approach would traverse the tree and record only the existing node values.
For example:
Tree A: Tree B:
1 1
/ \
2 2
Both produce:
[1,2]