Serialize and Deserialize Binary Tree in DSA Java - Time & Space Complexity
We want to understand how long it takes to convert a binary tree into a string and back.
How does the time needed grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
// Serialize: convert tree to string
public String serialize(TreeNode root) {
if (root == null) return "#,";
return root.val + "," + serialize(root.left) + serialize(root.right);
}
// Deserialize: convert string back to tree
public TreeNode deserialize(Queue<String> nodes) {
String val = nodes.poll();
if (val.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = deserialize(nodes);
node.right = deserialize(nodes);
return node;
}
This code turns a binary tree into a string using preorder traversal and then rebuilds it from that string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once in both serialize and deserialize.
- How many times: Each node is processed exactly once during serialization and once during deserialization.
As the tree grows, the number of nodes increases, so the work grows with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 calls (10 nodes for serialize + 10 for deserialize) |
| 100 | About 200 calls |
| 1000 | About 2000 calls |
Pattern observation: The total work grows roughly twice the number of nodes, so it grows linearly with input size.
Time Complexity: O(n)
This means the time to serialize and deserialize grows directly in proportion to the number of nodes in the tree.
[X] Wrong: "Serialization or deserialization takes more than linear time because of string operations or recursion overhead."
[OK] Correct: Each node is visited once, and string concatenation or queue operations happen in constant time per node, so overall time stays linear.
Understanding this linear time complexity helps you explain how your code scales with tree size, a key skill in interviews.
"What if we changed the traversal order from preorder to inorder for serialization? How would the time complexity change?"
Practice
serialize and deserialize methods in the context of a binary tree?Solution
Step 1: Understand serialization
Serialization means converting a binary tree into a string format so it can be stored or sent easily.Step 2: Understand deserialization
Deserialization means converting the string back into the original binary tree structure.Final Answer:
Convert a binary tree to a string and back to a tree -> Option DQuick Check:
Serialize/Deserialize = Convert tree to/from string [OK]
- Confusing serialization with sorting
- Thinking it deletes nodes
- Mixing with tree height calculation
Solution
Step 1: Identify return type for serialization
Serialization converts a tree to a string, so the return type must be String.Step 2: Check method parameters
The method should take the root node of the tree as input, so parameter is TreeNode root.Final Answer:
public String serialize(TreeNode root) -> Option CQuick Check:
Serialize returns String from TreeNode [OK]
- Using void return type for serialize
- Confusing serialize with deserialize signature
- Returning int instead of String
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);
}
Solution
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 (#).Step 2: Build string with commas and '#' for nulls
Concatenate values and null markers with commas: "1,2,#,#,3,4,#,#,5,#,#,"Final Answer:
1,2,#,#,3,4,#,#,5,#,#, -> Option BQuick Check:
Preorder + nulls = 1,2,#,#,3,4,#,#,5,#,#, [OK]
- Missing null markers (#)
- Wrong traversal order
- Omitting trailing commas
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;
}
Solution
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.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.Final Answer:
The index variable should be static or global to maintain state across recursive calls -> Option AQuick Check:
Index must persist across calls [OK]
- Making index local causing reset each call
- Wrong delimiter in split
- Incorrect return type
Solution
Step 1: Choose traversal and null markers
Preorder traversal with '#' for nulls ensures structure is preserved, including negative and zero values.Step 2: Parse integers correctly
Integer.parseInt handles negative, zero, and positive integers correctly during deserialization.Final Answer:
Use preorder traversal with ',' as separator and '#' for nulls; parse integers with Integer.parseInt during deserialization -> Option AQuick Check:
Preorder + '#' + Integer.parseInt handles all integers [OK]
- Skipping null markers causing wrong tree
- Ignoring negative values
- Using traversal without nulls losing structure
Ready to prove it?
Pass the test and this pattern moves unknown
