Serialize and Deserialize Binary Tree – Solution & Complexity

Solution Walkthrough

  1. Step 1: Record null children explicitly

    • A preorder traversal alone does not uniquely identify a binary tree, because you cannot tell where a subtree ends.
    • Emitting a sentinel token like # for every null child makes the preorder stream unambiguous: every node is followed immediately by its complete left subtree and then its complete right subtree.
  2. Step 2: Deserialize with a shared token cursor

    • Split the serialized string by , and maintain a single cursor index.
    • Read the next token: if it is #, return None; otherwise construct TreeNode(int(token)), recursively build .left, then recursively build .right.
  3. Step 3: Optimal O(n) preorder codec

    • Both serialize and deserialize visit every node and null pointer once: O(n) time and O(n) space.
    def serialize_and_deserialize(root: TreeNode) -> TreeNode:
        def serialize(node: TreeNode) -> str:
            out: list[str] = []
            def dfs(curr):
                if not curr:
                    out.append("#")
                    return
                out.append(str(curr.val))
                dfs(curr.left)
                dfs(curr.right)
            dfs(node)
            return ",".join(out)
    
        def deserialize(data: str) -> TreeNode:
            tokens = data.split(",")
            idx = 0
            def dfs():
                nonlocal idx
                tok = tokens[idx]
                idx += 1
                if tok == "#":
                    return None
                node = TreeNode(int(tok))
                node.left = dfs()
                node.right = dfs()
                return node
            return dfs()
    
        return deserialize(serialize(root))
  4. Step 4: Common mistakes

    • Treating node value 0 as falsy (if (!val)) instead of checking for the # sentinel.
    • Calling Array.shift() inside the deserialization loop, which turns O(n) into O(n^2); use an index pointer instead.

FAQ