↻one more pass.
Trees · Hard

Serialize and Deserialize Binary Tree: the idea to remember.

Convert any binary tree to text and reconstruct its exact structure and values.

Solve on LeetCode ↗

The core insight

Write preorder values and null markers. Decode in the same order, consuming one token for each subtree root.

Why it works

A null marker ends a subtree. A value must be followed by exactly its left subtree and right subtree, making the encoding unambiguous.

The mistake to avoid

Traversal values without null markers lose shape. Reset the decoding position for every call.

Time: O(n)Space: O(n) tokens and O(h) recursion

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

class Codec {
    String serialize(TreeNode root) {
        StringBuilder out = new StringBuilder(); write(root, out); return out.toString();
    }
    void write(TreeNode node, StringBuilder out) {
        if (node == null) { out.append("#,"); return; }
        out.append(node.val).append(','); write(node.left, out); write(node.right, out);
    }
    TreeNode deserialize(String text) {
        Deque<String> tokens = new ArrayDeque<>(Arrays.asList(text.split(",")));
        return read(tokens);
    }
    TreeNode read(Deque<String> tokens) {
        String token = tokens.remove();
        if (token.equals("#")) return null;
        TreeNode node = new TreeNode(Integer.parseInt(token));
        node.left = read(tokens); node.right = read(tokens); return node;
    }
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.