297. Serialize and Deserialize Binary Tree
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a pair of functions: one to serialize a binary tree into a string, and another to deserialize that string back into the original tree. The core challenge is to encode the tree's structure—the parent-child relationships—in the string format. A simple in-order traversal would only give us the node values in a sequence, but not the structure. For example, a tree with root 2, left child 1, right child 3, and a tree with root 1, right child 2, then its right child 3, can have the same in-order traversal 1, 2, 3. To uniquely reconstruct the tree, we must also encode the null children.
Solution
Serialize and Deserialize Binary Tree in Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = []
def dfs(node):
# Pre-order traversal to serialize
if not node:
res.append("N") # Use "N" for null nodes
return
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ",".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
vals = data.split(',')
self.i = 0 # Use a class member as a pointer to the current value
def dfs():
# If the current value is the null marker, this is a null node.
if vals[self.i] == "N":
self.i += 1
return None
# Create a new node with the current value.
node = TreeNode(int(vals[self.i]))
self.i += 1
# Recursively build the left and right subtrees.
node.left = dfs()
node.right = dfs()
return node
return dfs()
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))
Serialize and Deserialize Binary Tree in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Codec {
private static final String NULL_SYMBOL = "N";
private static final String SEPARATOR = ",";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
return sb.toString();
}
// Helper for pre-order traversal serialization
private void serializeHelper(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(NULL_SYMBOL).append(SEPARATOR);
return;
}
sb.append(root.val).append(SEPARATOR);
serializeHelper(root.left, sb);
serializeHelper(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.isEmpty()) {
return null;
}
Queue<String> nodes = new LinkedList<>(Arrays.asList(data.split(SEPARATOR)));
return deserializeHelper(nodes);
}
// Helper for deserialization from a queue of values
private TreeNode deserializeHelper(Queue<String> nodes) {
String val = nodes.poll();
if (val.equals(NULL_SYMBOL)) {
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = deserializeHelper(nodes);
node.right = deserializeHelper(nodes);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));
Serialize and Deserialize Binary Tree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <string>
#include <sstream>
class Codec {
public>
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
serializeHelper(root, out);
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
return deserializeHelper(in);
}
private:
// Helper function for serialization using pre-order traversal
void serializeHelper(TreeNode* root, ostringstream& out) {
if (!root) {
// Use 'N' to represent a null node
// Use spaces as separators, which works well with stringstream
out << "N ";
return;
}
// Append current node's value
out << root->val << " ";
// Recursively serialize left and right subtrees
serializeHelper(root->left, out);
serializeHelper(root->right, out);
}
// Helper function for deserialization
TreeNode* deserializeHelper(istringstream& in) {
string val;
// Read the next value from the stream
in >> val;
if (val == "N") {
// If it's a null marker, return nullptr
return nullptr;
}
// Create a new node with the parsed value
TreeNode* node = new TreeNode(stoi(val));
// Recursively build the left and right subtrees
node->left = deserializeHelper(in);
node->right = deserializeHelper(in);
return node;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
Serialize and Deserialize Binary Tree in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/*
* Encodes a tree to a single string.
*/
function serialize(root: TreeNode | null): string {
const res: string[] = [];
function dfs(node: TreeNode | null) {
// Pre-order traversal for serialization
if (!node) {
res.push('N'); // Use 'N' for null nodes
return;
}
res.push(String(node.val));
dfs(node.left);
dfs(node.right);
}
dfs(root);
return res.join(',');
};
/*
* Decodes your encoded data to tree.
*/
function deserialize(data: string): TreeNode | null {
if (!data) {
return null;
}
const vals = data.split(',');
let i = 0; // Use a shared index to track position in the vals array
function dfs(): TreeNode | null {
// If the current value indicates a null node
if (vals[i] === 'N') {
i++;
return null;
}
// Create a new node with the current value
const node = new TreeNode(parseInt(vals[i]));
i++;
// Recursively build left and right subtrees
node.left = dfs();
node.right = dfs();
return node;
}
return dfs();
};
/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.