Bird
Raised Fist0
DSA Javaprogramming~20 mins

Serialize and Deserialize Binary Tree in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Tree Serialization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Preorder Serialization
What is the output of the following Java code that serializes a binary tree using preorder traversal with '#' as null marker and ',' as separator?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int v) { val = v; }
}

public class SerializeTree {
    public static String serialize(TreeNode root) {
        if (root == null) return "#";
        return root.val + "," + serialize(root.left) + "," + serialize(root.right);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(5);
        System.out.println(serialize(root));
    }
}
A1,2,3,#,#,4,#,#,5,#,#
B1,2,#,#,3,4,#,#,5,#,#
C1,2,#,#,3,4,#,#,5,#
D1,2,#,3,4,#,#,5,#,#
Attempts:
2 left
💡 Hint
Think about preorder traversal: root, left subtree, right subtree. Use '#' for null children.
❓ Predict Output
intermediate
2:00remaining
Output of Deserialization Result
Given the serialized string "1,2,#,#,3,4,#,#,5,#,#", what is the value of the right child's right child node after deserialization?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int v) { val = v; }
}

public class DeserializeTree {
    static int index = 0;
    public static TreeNode deserialize(String[] data) {
        if (index >= data.length || data[index].equals("#")) {
            index++;
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(data[index++]));
        node.left = deserialize(data);
        node.right = deserialize(data);
        return node;
    }

    public static void main(String[] args) {
        String serialized = "1,2,#,#,3,4,#,#,5,#,#";
        String[] data = serialized.split(",");
        TreeNode root = deserialize(data);
        System.out.println(root.right.right.val);
    }
}
A5
B4
C3
D2
Attempts:
2 left
💡 Hint
Trace the deserialization steps carefully following preorder order.
🔧 Debug
advanced
2:00remaining
Identify the Bug in Serialization Code
What error will occur when running this serialization code for a binary tree?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int v) { val = v; }
}

public class SerializeTree {
    public static String serialize(TreeNode root) {
        if (root == null) return "#";
        return serialize(root.left) + "," + root.val + "," + serialize(root.right);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        System.out.println(serialize(root));
    }
}
AThe code throws a NullPointerException at runtime.
BThe output is '#,2,#,1,#,3,#' which is correct preorder serialization.
CThe output is '1,2,#,#,3,#,#' which is correct preorder serialization.
DThe output is '#,2,#,1,#,3,#' but this is inorder traversal, not preorder.
Attempts:
2 left
💡 Hint
Check the order of concatenation in the return statement.
📝 Syntax
advanced
2:00remaining
Syntax Error in Deserialization Code
Which option contains the correct fix to this syntax error in deserialization code snippet?
DSA Java
public TreeNode deserialize(String[] data) {
    if (data[index] == "#") {
        index++
        return null;
    }
    TreeNode node = new TreeNode(Integer.parseInt(data[index++]));
    node.left = deserialize(data);
    node.right = deserialize(data);
    return node;
}
ADeclare index as static int index = 0 outside the method.
BChange == to equals: if (data[index].equals("#")) { index++; return null; }
CAdd semicolon after index++: index++;
DReplace TreeNode with Node in method signature.
Attempts:
2 left
💡 Hint
Look for missing punctuation causing syntax error.
🚀 Application
expert
3:00remaining
Number of Nodes After Deserialization
Given the serialized string "10,5,#,#,15,12,#,#,20,#,#", how many nodes does the deserialized binary tree contain?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int v) { val = v; }
}

public class DeserializeTree {
    static int index = 0;
    public static TreeNode deserialize(String[] data) {
        if (index >= data.length || data[index].equals("#")) {
            index++;
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(data[index++]));
        node.left = deserialize(data);
        node.right = deserialize(data);
        return node;
    }

    public static int countNodes(TreeNode root) {
        if (root == null) return 0;
        return 1 + countNodes(root.left) + countNodes(root.right);
    }

    public static void main(String[] args) {
        String serialized = "10,5,#,#,15,12,#,#,20,#,#";
        String[] data = serialized.split(",");
        TreeNode root = deserialize(data);
        System.out.println(countNodes(root));
    }
}
A5
B6
C7
D8
Attempts:
2 left
💡 Hint
Count all non-null nodes in the tree after deserialization.

Practice

(1/5)
1. What is the main purpose of serialize and deserialize methods in the context of a binary tree?
easy
A. Delete all nodes in a binary tree
B. Sort the nodes of a binary tree in ascending order
C. Find the height of a binary tree
D. Convert a binary tree to a string and back to a tree

Solution

  1. Step 1: Understand serialization

    Serialization means converting a binary tree into a string format so it can be stored or sent easily.
  2. Step 2: Understand deserialization

    Deserialization means converting the string back into the original binary tree structure.
  3. Final Answer:

    Convert a binary tree to a string and back to a tree -> Option D
  4. Quick Check:

    Serialize/Deserialize = Convert tree to/from string [OK]
Hint: Serialization means tree to string, deserialization reverses it [OK]
Common Mistakes:
  • Confusing serialization with sorting
  • Thinking it deletes nodes
  • Mixing with tree height calculation
2. Which of the following is the correct Java method signature for a serialize function that converts a binary tree to a string?
easy
A. public int serialize(TreeNode root)
B. public void serialize(TreeNode root)
C. public String serialize(TreeNode root)
D. public TreeNode serialize(String data)

Solution

  1. Step 1: Identify return type for serialization

    Serialization converts a tree to a string, so the return type must be String.
  2. Step 2: Check method parameters

    The method should take the root node of the tree as input, so parameter is TreeNode root.
  3. Final Answer:

    public String serialize(TreeNode root) -> Option C
  4. Quick Check:

    Serialize returns String from TreeNode [OK]
Hint: Serialize returns string, takes root node as input [OK]
Common Mistakes:
  • Using void return type for serialize
  • Confusing serialize with deserialize signature
  • Returning int instead of String
3. Given the following code snippet for serialization using preorder traversal with '#' as null marker and ',' as separator, what is the output string for the tree below? Tree:

    1
   / \
  2   3
     / \
    4   5
Code snippet:

void serializeHelper(TreeNode root, StringBuilder sb) {
  if (root == null) {
    sb.append("#,");
    return;
  }
  sb.append(root.val).append(",");
  serializeHelper(root.left, sb);
  serializeHelper(root.right, sb);
}
medium
A. 1,2,#,#,3,4,#,#,5,#
B. 1,2,#,#,3,4,#,#,5,#,#,
C. 1,3,2,#,#,4,#,#,5,#,#,
D. 1,2,3,4,5,#,#,#,#,#,#,

Solution

  1. Step 1: Perform preorder traversal with null markers

    Visit root: 1, then left subtree: 2, left null (#), right null (#), then right subtree: 3, left: 4, left null (#), right null (#), right: 5, left null (#), right null (#).
  2. Step 2: Build string with commas and '#' for nulls

    Concatenate values and null markers with commas: "1,2,#,#,3,4,#,#,5,#,#,"
  3. Final Answer:

    1,2,#,#,3,4,#,#,5,#,#, -> Option B
  4. Quick Check:

    Preorder + nulls = 1,2,#,#,3,4,#,#,5,#,#, [OK]
Hint: Preorder serialize: root,left,right with '#' for null [OK]
Common Mistakes:
  • Missing null markers (#)
  • Wrong traversal order
  • Omitting trailing commas
4. Identify the bug in the following deserialize method that reconstructs a binary tree from a serialized string using preorder traversal with '#' as null marker:

int index = 0;
TreeNode deserialize(String data) {
  String[] nodes = data.split(",");
  if (nodes[index].equals("#")) {
    index++;
    return null;
  }
  TreeNode root = new TreeNode(Integer.parseInt(nodes[index++]));
  root.left = deserialize(data);
  root.right = deserialize(data);
  return root;
}
medium
A. The index variable should be static or global to maintain state across recursive calls
B. The split method should use ";" instead of ","
C. The method should return a String instead of TreeNode
D. The base case should check for empty string instead of "#"

Solution

  1. Step 1: Understand index usage in recursion

    The index variable tracks position in nodes array. It must keep its value across recursive calls to move forward correctly.
  2. Step 2: Identify scope problem

    Here, index is a local variable inside the method, so it resets to 0 on each call, causing infinite recursion or wrong tree.
  3. Final Answer:

    The index variable should be static or global to maintain state across recursive calls -> Option A
  4. Quick Check:

    Index must persist across calls [OK]
Hint: Index must be shared across recursion, use class/global variable [OK]
Common Mistakes:
  • Making index local causing reset each call
  • Wrong delimiter in split
  • Incorrect return type
5. You want to serialize a binary tree and then deserialize it back. However, your tree contains integer values that can be negative, zero, or positive. Which approach below correctly handles all integer values including negatives during serialization and deserialization?
hard
A. Use preorder traversal with ',' as separator and '#' for nulls; parse integers with Integer.parseInt during deserialization
B. Use inorder traversal without null markers; split by spaces; parse integers with Integer.parseInt
C. Use level order traversal but skip null nodes; separate values by commas; parse integers with Integer.parseInt
D. Serialize only positive values and ignore negatives; use preorder traversal

Solution

  1. Step 1: Choose traversal and null markers

    Preorder traversal with '#' for nulls ensures structure is preserved, including negative and zero values.
  2. Step 2: Parse integers correctly

    Integer.parseInt handles negative, zero, and positive integers correctly during deserialization.
  3. Final Answer:

    Use preorder traversal with ',' as separator and '#' for nulls; parse integers with Integer.parseInt during deserialization -> Option A
  4. Quick Check:

    Preorder + '#' + Integer.parseInt handles all integers [OK]
Hint: Use preorder + '#' + Integer.parseInt for all integer values [OK]
Common Mistakes:
  • Skipping null markers causing wrong tree
  • Ignoring negative values
  • Using traversal without nulls losing structure
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard