1. Understand the problem

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

2. Signal: Recognize the pattern

The important clues are:

A natural solution is preorder DFS (Depth-First Search).

Preorder visits nodes in this order:

  1. Current node.
  2. Left subtree.
  3. Right subtree.

For every missing child, record a marker such as N.

3. Brute force: Why recording only node values fails

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]