Serialize and Deserialize Binary Tree
Hard
Topics
Serialization turns a tree into a string; deserialization turns that string back into a tree. Design the pair so that deserializing a serialized tree reproduces it exactly.
You may choose any string format you like. The only requirement is that the round trip is lossless — the rebuilt tree must have the same shape and the same values, including which children are missing.
LeetCode poses this as a Codec class with two methods. The judge here calls one function that serializes its argument and immediately deserializes the result, returning the rebuilt tree, and then compares that tree against the original. Your format is never inspected, only the round trip.
Example 1
null tokens are not padding — they are what says "no child here", and without them a parent with only a left child would read identically to one with only a right child. Whatever is produced has to rebuild exactly this tree when read back, so the two directions are judged together.Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5] Explanation: The rebuilt tree equals the original, which is the whole requirement.
Example 2
Input: root = [] Output: [] Explanation: An empty tree has to survive the round trip too.
Example 3
Input: root = [1,2] Output: [1,2] Explanation: A node with only a left child — the format must record that the right child is absent, or the shape is lost.
Constraints
- 0 <= number of nodes <= 10^4
- -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
The trap is thinking that a list of values is enough. It is not: [1,2] and [1,null,2] contain the same two values and are different trees, so any format that records only the values has already lost.
What has to be recorded is the absences. Once a marker is written for every missing child, the structure is fully determined and rebuilding needs no cleverness — the string can be consumed in exactly the order it was produced.
A pre-order walk makes that especially clean. Write the value, then recurse left, then right, emitting a sentinel for each null. Reading it back, the first token is the root, and the recursion consumes exactly as many tokens as its subtree produced, so the left call naturally stops where the right one begins. No lengths or brackets are needed.
A level-order format works just as well and is what this judge prints, but note the two are different: the sentinels sit in different places, and a format is only required to round-trip through itself.
Approach
- To serialize: walk pre-order. At a null, append a sentinel such as
#. At a node, append its value. Join the tokens with a separator that cannot appear inside a value. - To deserialize: split into tokens and walk them with a cursor. Read one token; if it is the sentinel, return null. Otherwise build a node from it, then recursively build its left subtree and then its right.
- The cursor must be shared across the recursion rather than restarted, since each call consumes a variable number of tokens.
- Negative values are why the separator matters: a value can begin with
-, so splitting on anything that appears inside a number corrupts the stream.
Walkthrough
root = [1,2,3,null,null,4,5]
1
/ \
2 3
/ \
4 5
serialize, pre-order with # for null
1 2 # # 3 4 # # 5 # #
deserialize, consuming left to right
1 -> node 1, build its left
2 -> node 2, build its left
# -> null
# -> null, so node 2 is done
3 -> node 1 right: node 3
4 -> node 4, then # # -> done
5 -> node 5, then # # -> done
The nulls are what make this unambiguous: without them the
token stream 1 2 3 4 5 could rebuild several shapes.Complexity
- Time — O(n): each node and each null marker is written once and read once.
- Space — O(n): the string holds one token per node plus one per absent child, and the recursion is as deep as the tree.
Common Pitfalls
- Omitting the null markers, which makes the format ambiguous — the single most common wrong answer.
- Restarting the token cursor inside the recursion. Each subtree consumes a different number of tokens, so the position has to be shared.
- Splitting on a character that can appear inside a value. A tree with negative numbers breaks a format that treats
-as a separator. - Using a sentinel that collides with a real value.
"0"or"-1"are values here, not markers. - Assuming the rebuilt tree only has to contain the same values. Shape is part of the comparison, which is what example 3 checks.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def roundTrip(self, root):
SENTINEL = "#"
def serialize(node, out):
if not node:
out.append(SENTINEL)
return
out.append(str(node.val))
serialize(node.left, out)
serialize(node.right, out)
tokens = []
serialize(root, tokens)
self._at = 0
def build(parts):
token = parts[self._at]
self._at += 1
if token == SENTINEL:
return None
node = TreeNode(int(token))
node.left = build(parts)
node.right = build(parts)
return node
return build(tokens)import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public TreeNode roundTrip(TreeNode root) {
tokens = new ArrayList<>();
serialize(root);
at = 0;
return build();
}
private List<String> tokens;
private int at;
private void serialize(TreeNode node) {
if (node == null) {
tokens.add("#");
return;
}
tokens.add(String.valueOf(node.val));
serialize(node.left);
serialize(node.right);
}
private TreeNode build() {
String token = tokens.get(at++);
if (token.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(token));
node.left = build();
node.right = build();
return node;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: TreeNode* roundTrip(TreeNode* root) {
const string SENTINEL = "#";
vector<string> tokens;
function<void(TreeNode*)> serialize = [&](TreeNode* node) {
if (!node) {
tokens.push_back(SENTINEL);
return;
}
tokens.push_back(to_string(node->val));
serialize(node->left);
serialize(node->right);
};
serialize(root);
size_t at = 0;
function<TreeNode*()> build = [&]() -> TreeNode* {
string token = tokens[at++];
if (token == SENTINEL) return nullptr;
TreeNode* node = new TreeNode(stoi(token));
node->left = build();
node->right = build();
return node;
};
return build();
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @return {TreeNode}
*/ var roundTrip = function(root) {
const SENTINEL = "#";
const tokens = [];
const serialize = (node) => {
if (!node) {
tokens.push(SENTINEL);
return;
}
tokens.push(String(node.val));
serialize(node.left);
serialize(node.right);
};
serialize(root);
let at = 0;
const build = () => {
const token = tokens[at++];
if (token === SENTINEL) return null;
const node = { val: parseInt(token, 10), left: null, right: null };
node.left = build();
node.right = build();
return node;
};
return build();
};