📖 Scenario: You are working on a system that needs to save and load binary trees efficiently. To do this, you will convert a binary tree into a string (serialize) and then rebuild the tree from that string (deserialize).This is like writing down a family tree on paper and later reading it back to recreate the same family tree structure.
🎯 Goal: Build two functions: one to convert a binary tree into a string, and another to convert that string back into the original binary tree.This helps in saving the tree to a file or sending it over a network.
📋 What You'll Learn
Create a simple binary tree node class called TreeNode with val, left, and right attributes.
Write a function serialize(root) that converts the tree into a string using preorder traversal and uses '#' to mark null nodes.
Write a function deserialize(data) that converts the string back into the original binary tree.
Test the serialization and deserialization by printing the preorder traversal of the rebuilt tree.
💡 Why This Matters
🌍 Real World
Saving and loading tree data structures in databases, files, or sending them over networks.
💼 Career
Understanding serialization is important for software engineers working with data storage, networking, and distributed systems.
Progress0 / 4 steps
1
Create the TreeNode class and build a sample tree
Create a class called TreeNode with an __init__ method that takes val, left, and right parameters. Then create a binary tree with root value 1, left child 2, and right child 3. The right child 3 should have two children: left 4 and right 5.
DSA Python
Hint
Define the TreeNode class first. Then create the root and its children exactly as described.
2
Create a helper variable for serialization separator
Create a variable called SEP and set it to the string ','. This will be used to separate node values in the serialized string.
DSA Python
Hint
Just create a variable named SEP and assign it the string ','.
3
Write the serialize and deserialize functions
Write a function serialize(root) that returns a string representing the tree using preorder traversal. Use SEP to separate values and '#' to represent null nodes. Then write a function deserialize(data) that rebuilds the tree from the string. Use a helper inner function with an iterator over the split data.
DSA Python
Hint
Use preorder traversal for serialization. Use recursion and '#' for nulls. For deserialization, split the string and use an iterator to rebuild the tree recursively.
4
Print the preorder traversal of the deserialized tree
Use serialize(root) to get the string, then use deserialize(serialized_data) to rebuild the tree. Finally, print the preorder traversal of the rebuilt tree by serializing it again.
DSA Python
Hint
First serialize the original tree, then deserialize it back, and finally print the serialization of the rebuilt tree.
Practice
(1/5)
1. What is the main purpose of serialize and deserialize functions in the context of a binary tree?
easy
A. Delete all nodes in a binary tree
B. Sort the nodes of a binary tree
C. Calculate the height of a binary tree
D. Convert a binary tree to a string and back to a 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 tree -> Option D
Quick Check:
Serialize + Deserialize = Convert tree to string and back [OK]
Hint: Serialization means tree to string, deserialization reverses it [OK]
Common Mistakes:
Confusing serialization with sorting
Thinking it deletes nodes
Mixing serialization with height calculation
2. Which of the following is the correct way to represent a null node during serialization in a binary tree using preorder traversal?
easy
A. Use a special marker like '#' or 'null'
B. Skip the null node completely
C. Use an empty string ''
D. Use the value 0
Solution
Step 1: Understand null node representation
During serialization, null nodes must be marked explicitly to preserve tree structure.
Step 2: Choose correct marker
Common practice is to use a special marker like '#' or 'null' to represent null nodes.
Final Answer:
Use a special marker like '#' or 'null' -> Option A
Quick Check:
Null nodes marked with '#' or 'null' [OK]
Hint: Mark null nodes explicitly with '#' or 'null' [OK]
Common Mistakes:
Skipping null nodes loses tree shape
Using empty string confuses parsing
Using 0 can be mistaken for a valid node
3. Given the following serialized string of a binary tree using preorder with '#' as null marker: 1,2,#,#,3,4,#,#,5,#,#, what is the inorder traversal of the deserialized tree?
medium
A. [2, 4, 1, 3, 5]
B. [1, 2, 3, 4, 5]
C. [2, 1, 4, 3, 5]
D. [1, 3, 2, 4, 5]
Solution
Step 1: Reconstruct the tree from serialization
The string represents preorder: root=1, left=2, left's children null, right=3, left=4, right=5.
Inorder: left subtree (2), root (1), left subtree of right child (4), root of right child (3), right subtree (5) -> [2, 1, 4, 3, 5]
Final Answer:
[2, 1, 4, 3, 5] -> Option C
Quick Check:
Inorder of deserialized tree = [2, 1, 4, 3, 5] [OK]
Hint: Draw tree from preorder, then do inorder traversal [OK]
Common Mistakes:
Mixing preorder and inorder orders
Ignoring null markers during reconstruction
Swapping left and right children
4. Consider this buggy deserialize function snippet for a binary tree serialized with preorder and '#' as null marker:
def deserialize(data):
def helper():
val = next(vals)
if val == '#':
return None
node = TreeNode(int(val))
node.left = helper()
node.right = helper()
return node
vals = iter(data.split(','))
return helper()
What is the likely cause of a StopIteration error during deserialization?
medium
A. The helper function does not return the root node
B. The input string is missing some null markers
C. The split method is used incorrectly
D. The TreeNode constructor is called with a string instead of int
Solution
Step 1: Understand StopIteration cause
StopIteration occurs when iterator runs out of elements unexpectedly.
Step 2: Check input data correctness
If null markers '#' are missing, helper calls next(vals) more times than available, causing StopIteration.
Final Answer:
The input string is missing some null markers -> Option B
Quick Check:
Missing '#' causes StopIteration [OK]
Hint: Check if all null nodes are marked to avoid StopIteration [OK]
Common Mistakes:
Thinking helper must return root explicitly
Blaming split method for StopIteration
Confusing int conversion error with StopIteration
5. You want to serialize a binary tree and then deserialize it back. However, the tree can contain negative and zero values. Which serialization approach below correctly handles all integer values including zero and negative numbers without confusion?
hard
A. Serialize using preorder with comma-separated values and 'null' for null nodes
B. Serialize using comma-separated values but skip null nodes
C. Serialize using preorder with space-separated values and '#' for null nodes
D. Serialize using preorder with comma-separated values and '0' for null nodes
Solution
Step 1: Identify safe null marker
Using '0' as null marker is unsafe because zero can be a valid node value.
Step 2: Choose clear null marker and separator
Using 'null' as null marker with comma separator clearly distinguishes null nodes and supports negative and zero values.
Final Answer:
Serialize using preorder with comma-separated values and 'null' for null nodes -> Option A
Quick Check:
'null' marker avoids confusion with zero or negative values [OK]
Hint: Use 'null' marker, not '0', to handle zero and negatives [OK]
Common Mistakes:
Using '0' as null marker causes confusion
Skipping null nodes loses tree shape
Using space separator can cause parsing issues
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.