Serialize and Deserialize Binary Tree in Python and Java
In this tutorial, we will learn LeetCode #297: Serialize and Deserialize Binary Tree in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Serialize and Deserialize Binary Tree Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use preorder traversal because it gives a clean and optimized solution.
Example input: root = [5,2,8,null,3] Expected result: Output: serialized then restored tree Explanation: Preorder keeps structure with null markers.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: root = [5,2,8,null,3] Approach: preorder traversal We update variables step by step until we reach: Output: serialized then restored tree
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why preorder traversal is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. root = [5,2,8,null,3] We will solve it using preorder traversal. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: serialized then restored tree Why? Preorder keeps structure with null markers.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: serialized then restored tree
Example 1
Input: root = [5,2,8,null,3] Output: Output: serialized then restored tree Explanation: Preorder keeps structure with null markers.
Example 2
Input: root = [1,2,3,null,null,4,5] Output: serialized and deserialized tree Explanation: The tree can be converted to a string and rebuilt.
Python Code
Here is the complete Python solution for LeetCode #297.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class TreeCodec:
def serialize(self, root):
values = []
def dfs(node):
if not node:
values.append("N")
return
values.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ",".join(values)
def deserialize(self, data):
values = iter(data.split(","))
def dfs():
value = next(values)
if value == "N":
return None
node = TreeNode(int(value))
node.left = dfs()
node.right = dfs()
return node
return dfs()
codec = TreeCodec()
root = TreeNode(7, TreeNode(3), TreeNode(9, TreeNode(8), None))
text = codec.serialize(root)
new_root = codec.deserialize(text)
print(text) # Output: 7,3,N,N,9,8,N,N,N
print(codec.serialize(new_root)) # Output: 7,3,N,N,9,8,N,N,NJava Code
Here is the complete Java solution for LeetCode #297.
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
class TreeCodec {
public String serialize(TreeNode root) {
StringBuilder result = new StringBuilder();
build(root, result);
return result.toString();
}
private void build(TreeNode node, StringBuilder result) {
if (node == null) {
result.append("N,");
return;
}
result.append(node.val).append(',');
build(node.left, result);
build(node.right, result);
}
public TreeNode deserialize(String data) {
Queue<String> values = new LinkedList<>();
for (String value : data.split(",")) values.offer(value);
return buildTree(values);
}
private TreeNode buildTree(Queue<String> values) {
String value = values.poll();
if (value.equals("N")) return null;
TreeNode node = new TreeNode(Integer.parseInt(value));
node.left = buildTree(values);
node.right = buildTree(values);
return node;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(7);
root.left = new TreeNode(3);
root.right = new TreeNode(9);
root.right.left = new TreeNode(8);
TreeCodec codec = new TreeCodec();
String text = codec.serialize(root);
TreeNode newRoot = codec.deserialize(text);
System.out.println(text); // 7,3,N,N,9,8,N,N,N,
System.out.println(codec.serialize(newRoot)); // 7,3,N,N,9,8,N,N,N,
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #297: Serialize and Deserialize Binary Tree becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.