Serialize and Deserialize Binary Tree (LeetCode 297): Solution and Explanation

Hard
String
Tree
Depth First Search
Breadth First Search
Design
Binary Tree

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. In serialize, return "[]" for an empty tree. Otherwise start a queue with the root.
  2. Pop a node. If it exists, append its value and push both children, even when they are None. If it is None, append "null".
  3. When the queue empties, join the tokens with commas and wrap them in brackets.
  4. In deserialize, return None for "[]". Otherwise strip the brackets, split on commas, and create the root from the first token.
  5. Keep a queue of nodes awaiting children and an index i starting at 1. For each popped node, read vals[i] as its left child and vals[i + 1] as its right child, creating and enqueuing a node for any token that is not "null".
  6. Advance i by 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]
  1. 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.
  2. The two None entries write null twice. Nodes 4 and 5 are written and each pushes two None children, which add four more null tokens.
  3. The result is [1,2,3,null,null,4,5,null,null,null,null].
  4. Deserialize creates root 1 and sets i = 1. Popping 1 reads 2 and 3 as its children and enqueues both, so i becomes 3.
  5. Popping 2 reads two null tokens, so it gets no children. Popping 3 reads 4 and 5, which are attached and enqueued.
  6. Popping 4 and 5 each consume two null tokens. 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 root

Time and space complexity

Time

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.

Space

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.