SDE & MLE Prep

297. Serialize and Deserialize Binary Tree

Problem

Design a Codec whose serialize(root) turns a binary tree into a string and deserialize(data) rebuilds exactly the same tree from that string. Any format works as long as the round trip is exact.

Example: deserialize(serialize([1,2,3,null,null,4,5])) → [1,2,3,null,null,4,5]

Constraints: up to 10⁴ nodes; values in [−1000, 1000].

Preorder with explicit null markers (#) uniquely identifies a tree. Deserialize by consuming tokens in the same preorder.

    1
   / \        "1,2,#,#,3,4,#,#,5,#,#"
  2   3
     / \
    4   5

Complexity: O(n) both ways.

class Codec:
    def serialize(self, root: Optional[TreeNode]) -> str:
        out = []

        def dfs(node):
            if not node:
                out.append("#")
                return
            out.append(str(node.val))
            dfs(node.left)
            dfs(node.right)

        dfs(root)
        return ",".join(out)

    def deserialize(self, data: str) -> Optional[TreeNode]:
        it = iter(data.split(","))

        def build():
            v = next(it)
            if v == "#":
                return None
            node = TreeNode(int(v))
            node.left = build()
            node.right = build()
            return node

        return build()