CMD Guide
HomeDSAAdvanced Patterns

hard Serialize and Deserialize Binary Tree

Problem Statement

Given a binary tree, your task is to create two functions.

one for serializing the tree into a string format and another for deserializing the string back into the tree.

The serialized string should retain all the tree nodes and their connections, allowing for reconstruction without any loss of data.

Examples

  1. Example 1:

    • Input: [1,2,3,null,null,4,5]
    • Expected Output: [1,2,3,null,null,4,5]
    • Justification: The tree has the structure:
        1
       / \
      2   3
         / \
        4   5
      
      When serialized and then deserialized, it should retain the exact same structure.
  2. Example 2:

    • Input: [1,null,2,3]
    • Expected Output: [1,null,2,3]
    • Justification: The tree has the structure:
        1
         \
          2
         /
        3
      
      When serialized and then deserialized, it should retain the exact same structure.
  3. Example 3:

    • Input: [5,4,7,3,null,null,null,2]
    • Expected Output: [5,4,7,3,null,null,null,2]
    • Justification: The tree has the structure:
             5
           /   \
          4     7
         /     
        3    
       /
      2
      

Constraints:

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT — Serialize and Deserialize Binary Tree (problem)

0. Pattern family

Family: General binary tree SerDe with null sentinels

Why this pattern: Without BST bounds, structure is free-form: every missing child must be marked or the decode tree forks ambiguously.

1. Recognition · template (K12)

Preorder: visit node; if null write '#'; else write val and recurse left/right. Or BFS: queue levels with nulls, optionally trim trailing nulls carefully on decode.

2. Complexity derivation (K11)

Θ(n) time and Θ(n) output size (values + null tokens). Stack/queue O(h) or O(n) worst.

3. When-NOT (K12)

BST-only → omit nulls with bounds. N-ary → child count markers. Cyclic graph → id + back-references. Do not emit full 2^h array.

4. Edge / hand-run (K13)

[] / null root. Skewed chain. Full complete tree. Values that look like sentinels → choose delimiter/encoding that cannot collide (e.g. length forms).

5. Interviewer follow-ups & drills

Q1. Minimum information theoretically?
Model answer: Any encoding of Catalan-many shapes + labels.

Q2. BFS trailing nulls?
Model answer: Must not drop nulls that are needed as left-child placeholders.

Q3. Language string split cost?
Model answer: Prefer tokenizer walking indices for O(n).

✅ Solution Serialize and Deserialize Binary Tree

Problem Statement

Given a binary tree, your task is to create two functions.

one for serializing the tree into a string format and another for deserializing the string back into the tree.

The serialized string should retain all the tree nodes and their connections, allowing for reconstruction without any loss of data.

Examples

  1. Example 1:

    • Input: [1,2,3,null,null,4,5]
    • Expected Output: [1,2,3,null,null,4,5]
    • Justification: The tree has the structure:
        1
       / \
      2   3
         / \
        4   5
      
      When serialized and then deserialized, it should retain the exact same structure.
  2. Example 2:

    • Input: [1,null,2,3]
    • Expected Output: [1,null,2,3]
    • Justification: The tree has the structure:
        1
         \
          2
         /
        3
      
      When serialized and then deserialized, it should retain the exact same structure.
  3. Example 3:

    • Input: [5,4,7,3,null,null,null,2]
    • Expected Output: [5,4,7,3,null,null,null,2]
    • Justification: The tree has the structure:
             5
           /   \
          4     7
         /     
        3    
       /
      2
      

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000

Solution

To serialize a binary tree, we will traverse it in a pre-order fashion (root-left-right) and generate a string representation. When we encounter a null value, we'll represent it with a special character, say "X". The serialized string will have each value separated by a comma.

For deserialization, we will split the string on commas and use a queue to help in the reconstruction. We'll take the front of the queue and check if it's "X". If it is, then it's a null node, otherwise, we create a new node with the value. The same approach applies recursively for the left and right children.

  1. Serialization:
    • Start from the root.
    • If the current node is null, append "X," to the result string.
    • If not null, append its value and a comma to the result string.
    • Recursively serialize the left subtree.
    • Recursively serialize the right subtree.
  2. Deserialization:
    • Split the string by comma to get a list of nodes.
    • Use a queue to facilitate tree reconstruction.
    • For each value in the list:
      • If it's "X", return null.
      • Otherwise, create a new node.
      • Recursively deserialize the left and right children.

Algorithm Walkthrough:

Given the input: [1,2,3,null,null,4,5].

Serialization

Image
Image
  • Start with root: 1. Add "1," to the result string.
  • Go left: 2. Add "2," to the result string.
  • Go left: null. Add "X," to the result string.
  • Go back and go right: null. Add "X," to the result string.
  • Go back to 1 and go right: 3. Add "3," to the result string.
  • Go left: 4. Add "4," to the result string.
  • Left and right of 4 are null. Add "X,X," to the result string.
  • Go back to 3 and go right: 5. Add "5," to the result string.
  • Left and right of 5 are null. Add "X,X," to the result string.
  • Resulting serialized string: "1,2,X,X,3,4,X,X,5,X,X,".

Deserialization

Image
Image
  • Split string by comma: ["1","2","X","X","3","4","X","X","5","X","X"].
  • Start with "1". Create a node with value 1.
  • Move to next value "2". Create a left child with value 2.
  • Next is "X". So, the left of 2 is null.
  • Move to the next "X". Right of 2 is also null.
  • Next is "3". Create a right child for root with value 3.
  • Next is "4". Create a left child for 3 with value 4.
  • Two X's indicate the left and right children of 4 are null.
  • "5" is the right child of 3.
  • Two X's indicate the children of 5 are null.

Code

java
import java.util.*;

// Definition for a binary tree node.
//    public static class TreeNode {
//     int val;
//     TreeNode left;
//     TreeNode right;
//     TreeNode(int x) { val = x; }
//     TreeNode(int x, TreeNode left, TreeNode right) {  // Overloaded constructor
//         this.val = x;
//         this.left = left;
//         this.right = right;
//     }
// }

public class Solution {

  // Encodes a tree to a single string using a pre-order traversal.
  public String serialize(TreeNode root) {
    StringBuilder sb = new StringBuilder();
    serializeHelper(root, sb);
    return sb.toString();
  }

  private void serializeHelper(TreeNode node, StringBuilder sb) {
    // If the current node is null, append "X" to the result string.
    if (node == null) {
      sb.append("X,");
    } else {
      // Append the node value and then serialize left and right subtrees.
      sb.append(node.val + ",");
      serializeHelper(node.left, sb);
      serializeHelper(node.right, sb);
    }
  }

  // Decodes your encoded data to tree.
  public TreeNode deserialize(String data) {
    Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));
    return deserializeHelper(queue);
  }

  private TreeNode deserializeHelper(Queue<String> queue) {
    // Extract the value from the queue.
    String val = queue.poll();
    if (val.equals("X")) return null;
    // Create a node and then recursively deserialize left and right children.
    TreeNode node = new TreeNode(Integer.parseInt(val));
    node.left = deserializeHelper(queue);
    node.right = deserializeHelper(queue);
    return node;
  }

  public static void main(String[] args) {
    Solution solution = new Solution();
    TreeNode testTree = new TreeNode(
      1,
      new TreeNode(2),
      new TreeNode(3, new TreeNode(4), new TreeNode(5))
    );
    String serialized = solution.serialize(testTree);
    TreeNode deserialized = solution.deserialize(serialized);
    System.out.println("Serialized: " + serialized);
    System.out.println(
      "Deserialized (Serialized again for verification): " +
        solution.serialize(deserialized)
    );
  }
}

Complexity Analysis

Time Complexity

  • Serialization: We visit every node once and only once, which gives a time complexity of , where (n) is the number of nodes in the tree.
  • Deserialization: Similarly, for deserialization, we reconstruct every node once and only once, so the time complexity is also .

Space Complexity

  • Serialization: In the worst case, we have to append for every node and its two children. Additionally, there might be a considerable number of nulls (X), hence the space complexity would be .
  • Deserialization: The primary space consumption lies in the recursion stack, which would be , where (h) is the height of the tree. In the worst case, the tree could be skewed, making its height (n), so the space complexity would be .

🎯 STRICT STANDOUT — Solution Serialize and Deserialize Binary Tree

0. Pattern family

Family: Preorder null-marker codec

Why this pattern: Round-trip proof: the preorder decision sequence with explicit nulls is uniquely decodable by a single left-to-right cursor.

1. Recognition · template (K12)

ser(node): if not node: append '#'; else append val; ser(left); ser(right). deser: tok=next(); if tok=='#': return null; node=Tree(val); node.left=deser(); node.right=deser().

2. Complexity derivation (K11)

Tokens ≤ 2n+1 for binary tree → Θ(n).
Hand-run tree 1 / 2 3 with 2 having null children: '1,2,#,#,3,#,#' → rebuild same shape.

3. When-NOT (K12)

If only structure of BST needed → lighter BST codec. If n huge and sparse level-order without trim → wasteful.

4. Edge / hand-run (K13)

Only left children: 1,2,#,#,#, pattern careful — after 2's nulls, 1's right is #.
Root null → '#' only.

5. Interviewer follow-ups & drills

Q1. Why two nulls after a leaf?
Model answer: Leaf has two child slots both empty.

Q2. Iterative stack deser?
Model answer: Possible; must simulate the same preorder decisions.

Q3. Compare to clone pattern?
Model answer: SerDe goes through bytes; clone stays in-memory with map.

🧩 Pattern · Trees

Recognize it: Hierarchical data → recurse on children; BFS (queue) for level-order, DFS (recursion) for paths.

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 Don't fully get this? Learn it with Claude

Stuck on Serialize and Deserialize Binary Tree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Serialize and Deserialize Binary Tree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Serialize and Deserialize Binary Tree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Serialize and Deserialize Binary Tree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Serialize and Deserialize Binary Tree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes