Serialize and Deserialize Binary Tree in DSA C# - 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 grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int x) { val = x; }
}
public string Serialize(TreeNode root) {
if (root == null) return "#,";
return root.val + "," + Serialize(root.left) + Serialize(root.right);
}
public TreeNode Deserialize(ref string data) {
int comma = data.IndexOf(",");
string val = data.Substring(0, comma);
data = data.Substring(comma + 1);
if (val == "#") return null;
TreeNode node = new TreeNode(int.Parse(val));
node.left = Deserialize(ref data);
node.right = Deserialize(ref data);
return node;
}
This code converts a binary tree to 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 during serialization and deserialization.
- How many times: Exactly once per node in the tree, so n times for n nodes.
Each node is visited once to write or read its value.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to serialize or deserialize grows linearly with the number of nodes in the tree.
[X] Wrong: "Serialization takes more than linear time because of string operations inside recursion."
[OK] Correct: Although string operations happen, each node is still processed once, so the total work is proportional to n.
Understanding this linear time complexity helps you explain how your solution scales and why it is efficient for trees of any size.
"What if we changed the traversal from preorder to level order? 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 data structure like a binary tree into a string format that can be stored or transmitted.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 binary tree -> Option DQuick Check:
Serialize/Deserialize = Convert tree to/from string [OK]
- Confusing serialization with sorting
- Thinking serialization deletes nodes
- Assuming serialization finds tree height
Solution
Step 1: Identify return type for serialization
Serialization converts a tree to a string, so the return type must bestring.Step 2: Check method parameters
The method should take the root node of the tree as input, typicallyTreeNode 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,#,#", what is the inorder traversal of the deserialized tree?Solution
Step 1: Reconstruct tree from preorder string
Preorder: root=1, left subtree=2,#,# (2 with no children), right subtree=3,4,#,#,5,#,# (3 with left=4, right=5).Step 2: Perform inorder traversal (left, root, right)
Inorder: left subtree of 1 is 2, then root 1, then left subtree of 3 is 4, root 3, right subtree 5. So inorder is [2, 1, 4, 3, 5].Final Answer:
[2, 1, 4, 3, 5] -> Option BQuick Check:
Inorder matches reconstructed tree [OK]
- Mixing preorder and inorder traversal orders
- Ignoring null markers '#' in deserialization
- Incorrectly assigning left and right children
public TreeNode Deserialize(string data) {
var nodes = data.Split(',');
int index = 0;
return DeserializeHelper(nodes, ref index);
}
private TreeNode DeserializeHelper(string[] nodes, ref int index) {
if (index >= nodes.Length || nodes[index] == "#") {
index++;
return null;
}
TreeNode node = new TreeNode(int.Parse(nodes[index++]));
node.left = DeserializeHelper(nodes, ref index);
node.right = DeserializeHelper(nodes, ref index);
return node;
}
What is the main bug if index was passed without ref keyword?Solution
Step 1: Understand passing index by reference
Passingindexbyrefallows recursive calls to update the same variable, tracking position in the array.Step 2: Effect of missing
Ifrefindexis passed by value, each recursive call gets a copy, so updates won't reflect outside, causing repeated processing of same nodes and infinite recursion or wrong tree.Final Answer:
The index will not update correctly across recursive calls, causing infinite recursion or wrong tree -> Option AQuick Check:
Missing ref causes index not to update globally [OK]
- Assuming code won't compile without ref
- Thinking tree deserializes correctly without ref
- Confusing NullReferenceException with index issue
Solution
Step 1: Understand serialization requirements
To handle duplicates and nulls, serialization must record node values and null positions explicitly.Step 2: Evaluate options
Preorder with '#' for nulls and commas as separators records structure and values including duplicates. Inorder without nulls loses structure. Level order skipping nulls loses position info. Serializing only leaves loses tree shape.Final Answer:
Use preorder traversal with '#' for nulls and commas to separate nodes -> Option AQuick Check:
Preorder + null markers preserves full tree [OK]
- Skipping null nodes loses tree shape
- Using inorder without nulls loses structure
- Ignoring duplicate values in serialization
Ready to prove it?
Pass the test and this pattern moves unknown
