Serialize and Deserialize Binary Tree
Difficulty: Hard · Pattern: Trees & BST · LeetCode #297
Design a Codec class with:
serialize(root): encode a binary tree as a string.deserialize(data): decode that string back into the identical tree.
You choose the format. The tests call deserialize(serialize(root)) and compare the result with the original.
Examples
text
[1,2,3,null,null,4,5] → (any string) → [1,2,3,null,null,4,5]
[] → (any string) → []Hints
- A preorder traversal alone is ambiguous. Preorder with explicit null markers is not.
- When deserializing, consume tokens with an iterator: each call to
build()takes exactly one subtree's tokens.
Approach
Preorder + null markers:
text
1
/ \ → "1,2,#,#,3,4,#,#,5,#,#"
2 3
/ \
4 5serialize: visit the node, writingvalor#for null, then recurse left and right. Use an iterative stack to avoid recursion limits on deep trees.deserialize: split on,, thenbuild()reads the next token.#means return null. Otherwise create the node, then build its left subtree, then its right.
Why does this work? Every node contributes exactly one token and every missing child contributes one #, so the token stream fully determines the structure. Level-order with nulls (LeetCode's own format) works just as well. Use a delimiter so multi-digit and negative values parse unambiguously.
Complexity
Time: O(n) for each direction. Space: O(n) for the string.
Python solution
class Codec:
def serialize(self, root):
out, stack = [], [root]
while stack:
n = stack.pop()
if n is None:
out.append('#')
else:
out.append(str(n.val))
stack.append(n.right)
stack.append(n.left)
return ','.join(out)
def deserialize(self, data):
tokens = iter(data.split(','))
def build():
t = next(tokens)
if t == '#':
return None
node = TreeNode(int(t))
node.left = build()
node.right = build()
return node
return build()JavaScript solution
class Codec {
serialize(root) {
const out = [], stack = [root];
while (stack.length) {
const n = stack.pop();
if (!n) out.push('#');
else { out.push(String(n.val)); stack.push(n.right, n.left); }
}
return out.join(',');
}
deserialize(data) {
const t = data.split(',');
let i = 0;
const build = () => {
const tok = t[i++];
if (tok === '#') return null;
const node = new TreeNode(Number(tok));
node.left = build();
node.right = build();
return node;
};
return build();
}
}