Serialize and Deserialize Binary Tree in DSA Go - 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.
// Serialize converts a binary tree to a string
func serialize(root *TreeNode) string {
if root == nil {
return "#"
}
return fmt.Sprintf("%d,%s,%s", root.Val, serialize(root.Left), serialize(root.Right))
}
// Deserialize converts a string back to a binary tree
func deserialize(data string) *TreeNode {
vals := strings.Split(data, ",")
var index int
var build func() *TreeNode
build = func() *TreeNode {
if vals[index] == "#" {
index++
return nil
}
val, _ := strconv.Atoi(vals[index])
index++
node := &TreeNode{Val: val}
node.Left = build()
node.Right = build()
return node
}
return build()
}
This code turns a binary tree into a string and then rebuilds the tree from that string.
- Primary operation: Visiting each node once during serialization and deserialization.
- How many times: Exactly once per node in the tree.
Each node is processed once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The time grows in a straight line as the tree size grows.
Time Complexity: O(n)
This means the time to serialize or deserialize grows directly with the number of nodes.
[X] Wrong: "Serialization takes constant time because it just creates a string."
[OK] Correct: The string must include every node, so the process must visit all nodes, which takes time proportional to the tree size.
Understanding this helps you explain how tree data can be saved and restored efficiently, a common real-world need.
"What if we used a different traversal order (like inorder) for serialization? How would the time complexity change?"
Practice
serialize and deserialize functions for 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.Step 2: Understand deserialization
Deserialization means converting the string back into the original binary tree structure.Final Answer:
Convert a binary tree into a string and back to a tree -> Option AQuick Check:
Serialize/Deserialize = Convert tree to string and back [OK]
- Confusing serialization with sorting
- Thinking serialization deletes nodes
- Mixing serialization with tree height calculation
Solution
Step 1: Identify input and output types
Deserialize takes a string (serialized data) and returns a pointer to the root node of the tree.Step 2: Match function signature
func deserialize(data string) *TreeNode matches this: input is string, output is *TreeNode pointer.Final Answer:
func deserialize(data string) *TreeNode -> Option CQuick Check:
Deserialize input string, output tree node pointer [OK]
- Using int instead of string as input
- Returning string instead of tree node
- Confusing serialize and deserialize signatures
"1,2,#,#,3,4,#,#,5,#,#", what is the inorder traversal output of the deserialized tree?Solution
Step 1: Reconstruct tree from preorder string
Preorder: 1 (root), 2 (left child), # (left null), # (right null), 3 (right child), 4 (left), #, #, 5 (right), #, #.Step 2: Draw tree and find inorder traversal
Tree structure:
1
/ \
2 3
/ \
4 5
Inorder (left, root, right): 2, 1, 4, 3, 5Final Answer:
[2, 1, 4, 3, 5] -> Option DQuick Check:
Inorder traversal = [2,1,4,3,5] [OK]
- Mixing preorder and inorder traversal orders
- Ignoring null markers '#' in deserialization
- Incorrectly placing children nodes
func deserialize(data string) *TreeNode {
vals := strings.Split(data, ",")
var index int
var build func() *TreeNode
build = func() *TreeNode {
if vals[index] == "#" {
index++
return nil
}
node := &TreeNode{Val: vals[index]}
index++
node.Left = build()
node.Right = build()
return node
}
return build()
}Solution
Step 1: Check TreeNode.Val assignment
vals[index] is a string, but TreeNode.Val expects an int. Conversion is missing.Step 2: Identify fix
Use strconv.Atoi(vals[index]) to convert string to int before assigning.Final Answer:
TreeNode.Val should be converted from string to int -> Option AQuick Check:
String to int conversion missing [OK]
- Forgetting to convert string to int
- Changing index scope unnecessarily
- Misusing Split delimiter
Solution
Step 1: Understand serialization needs
To reconstruct the exact tree, we must record node order and null positions.Step 2: Evaluate options
Preorder with null markers records structure and values including duplicates. Inorder or postorder without nulls loses structure. Storing only values loses tree shape.Final Answer:
Use preorder traversal with a special marker for null nodes -> Option BQuick Check:
Preorder + null markers preserves structure and duplicates [OK]
- Ignoring null nodes in serialization
- Using inorder without nulls loses tree shape
- Assuming values alone define tree
Ready to prove it?
Pass the test and this pattern moves unknown
