Serialize and Deserialize Binary Tree (LeetCode 297): Solution and Explanation
Design a pair of functions: one turns a binary tree into a string, and the other rebuilds the exact same tree from that string. The format is up to you, as long as every tree round-trips without losing its values or shape.
Watch it run step by step
Try your own input and write the code →Intuition
The key difficulty is that a plain list of values loses structure. Many differently shaped trees share the same preorder, inorder or level order sequence. Any serialization has to record where children are missing, not just which values exist, so the format needs an explicit marker for null.
Once you include null markers, a single traversal is enough to pin the tree down. Level order is a natural choice because it mirrors how the tree reads on paper. You visit nodes with a queue, write each node's value, and when a child is missing you write null in its place. The string ends up as the familiar bracketed form, such as [1,2,3,null,null,4,5] plus a few trailing nulls.
Deserializing replays the same BFS. The first token is the root. Then you pop parents from a queue in the order they were written, and each parent consumes the next two tokens as its left and right children. A real value becomes a new node that also joins the queue, and a null leaves that child empty. Because writing and reading walk the tree in the same order, each token lands on exactly the slot it came from.
Approach: Level-order BFS with null markers
- In
serialize, return"[]"for an empty tree. Otherwise start a queue with the root. - Pop a node. If it exists, append its value and push both children, even when they are None. If it is None, append
"null". - When the queue empties, join the tokens with commas and wrap them in brackets.
- In
deserialize, return None for"[]". Otherwise strip the brackets, split on commas, and create the root from the first token. - Keep a queue of nodes awaiting children and an index
istarting at 1. For each popped node, readvals[i]as its left child andvals[i + 1]as its right child, creating and enqueuing a node for any token that is not"null". - Advance
iby one after each child slot and return the root once the queue is empty.
Step-by-step example
root = [1,2,3,null,null,4,5]
- Serialize pops 1, writes it, and pushes 2 and 3. Popping 2 writes 2 and pushes two None children. Popping 3 writes 3 and pushes 4 and 5.
- The two None entries write
nulltwice. Nodes 4 and 5 are written and each pushes two None children, which add four morenulltokens. - The result is
[1,2,3,null,null,4,5,null,null,null,null]. - Deserialize creates root 1 and sets
i = 1. Popping 1 reads 2 and 3 as its children and enqueues both, soibecomes 3. - Popping 2 reads two
nulltokens, so it gets no children. Popping 3 reads 4 and 5, which are attached and enqueued. - Popping 4 and 5 each consume two
nulltokens. The queue empties and the rebuilt tree matches the original.
Code: Python, Java, C++
1class Codec:
2 def serialize(self, root):
3 if not root: return "[]"
4 res = []
5 queue = collections.deque([root])
6 while queue:
7 node = queue.popleft()
8 if node:
9 res.append(str(node.val))
10 queue.append(node.left)
11 queue.append(node.right)
12 else:
13 res.append("null")
14 return "[" + ",".join(res) + "]"
15
16 def deserialize(self, data):
17 if data == "[]": return None
18 vals = data[1:-1].split(",")
19 root = TreeNode(int(vals[0]))
20 queue = collections.deque([root])
21 i = 1
22 while queue:
23 node = queue.popleft()
24 if i < len(vals) and vals[i] != "null":
25 node.left = TreeNode(int(vals[i]))
26 queue.append(node.left)
27 i += 1
28 if i < len(vals) and vals[i] != "null":
29 node.right = TreeNode(int(vals[i]))
30 queue.append(node.right)
31 i += 1
32 return root1public class Codec {
2 public String serialize(TreeNode root) {
3 if (root == null) return "[]";
4 StringBuilder res = new StringBuilder("[");
5 Queue<TreeNode> q = new LinkedList<>();
6 q.add(root);
7 while (!q.isEmpty()) {
8 TreeNode node = q.poll();
9 if (node == null) {
10 res.append("null,");
11 } else {
12 res.append(node.val + ",");
13 q.add(node.left);
14 q.add(node.right);
15 }
16 }
17 res.setLength(res.length() - 1);
18 res.append("]");
19 return res.toString();
20 }
21
22 public TreeNode deserialize(String data) {
23 if (data.equals("[]")) return null;
24 String[] vals = data.substring(1, data.length() - 1).split(",");
25 TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
26 Queue<TreeNode> q = new LinkedList<>();
27 q.add(root);
28 int i = 1;
29 while (!q.isEmpty()) {
30 TreeNode node = q.poll();
31 if (!vals[i].equals("null")) {
32 node.left = new TreeNode(Integer.parseInt(vals[i]));
33 q.add(node.left);
34 }
35 i++;
36 if (!vals[i].equals("null")) {
37 node.right = new TreeNode(Integer.parseInt(vals[i]));
38 q.add(node.right);
39 }
40 i++;
41 }
42 return root;
43 }
44}1class Codec {
2public:
3 string serialize(TreeNode* root) {
4 if (!root) return "[]";
5 string res = "[";
6 queue<TreeNode*> q;
7 q.push(root);
8 while (!q.empty()) {
9 TreeNode* node = q.front(); q.pop();
10 if (node) {
11 res += to_string(node->val) + ",";
12 q.push(node->left);
13 q.push(node->right);
14 } else {
15 res += "null,";
16 }
17 }
18 res.pop_back();
19 res += "]";
20 return res;
21 }
22
23 TreeNode* deserialize(string data) {
24 if (data == "[]") return nullptr;
25 string val;
26 stringstream ss(data.substr(1, data.size() - 2));
27 getline(ss, val, ',');
28 TreeNode* root = new TreeNode(stoi(val));
29 queue<TreeNode*> q;
30 q.push(root);
31 while (!q.empty()) {
32 TreeNode* node = q.front(); q.pop();
33 if (getline(ss, val, ',')) {
34 if (val != "null") {
35 node->left = new TreeNode(stoi(val));
36 q.push(node->left);
37 }
38 }
39 if (getline(ss, val, ',')) {
40 if (val != "null") {
41 node->right = new TreeNode(stoi(val));
42 q.push(node->right);
43 }
44 }
45 }
46 return root;
47 }
48};Time and space complexity
O(n)
Each node is enqueued and dequeued once in each direction, and the number of null markers is at most n + 1, so both functions do linear work. String joining and splitting are linear in the output length as well.
O(n)
The token list and output string have about 2n + 1 entries, and the BFS queue can hold up to a full level of nodes.
Other approaches
Preorder DFS with null markers (time O(n), space O(n))
Write the node value, then recursively serialize left and right, using a marker such as N for missing children. Deserialize by reading tokens with a shared iterator and rebuilding recursively in the same order. It is very compact to code but uses recursion depth equal to the tree height.
Trim trailing nulls (time O(n), space O(n))
Use the same BFS but drop the trailing null tokens at the end of the string. Deserialization already guards with i < len(vals), so it still works and the output is shorter, matching the format commonly used to display trees.
Common mistakes
- Leaving out null markers. Without them the deserializer cannot tell a missing left child from a missing right child.
- Reading tokens without checking
i < len(vals), which crashes when trailing nulls are trimmed. - Parsing values character by character. Values can be negative or have several digits, so split on a delimiter and convert each whole token with
int. - Serializing children in one order and reading them in another. Both functions must consume left before right.
Frequently asked questions
Why can't you serialize a binary tree with just its values?
A list of values does not record shape. Two trees with different structures can produce the same traversal sequence, so you need markers for missing children or a second traversal to reconstruct the tree uniquely.
Should I use BFS or DFS for serializing a binary tree?
Both work in O(n) time and space. BFS produces the familiar level order format and avoids deep recursion, while preorder DFS is shorter to write and pairs neatly with a recursive deserializer.
How is this different from serializing a binary search tree?
A BST can be rebuilt from its preorder alone, without null markers, because the ordering tells you where each value belongs. A general binary tree has no such ordering, so the shape has to be stored explicitly.