Serialize and Deserialize Binary Tree
The problem
Section titled “The problem”Design a class Codec with serialize(root), which returns a string, and
deserialize(data), which returns a tree with the same shape and values. The format is
up to you. Values can be negative, and the tree can be empty.
root = [1, 2, 3, null, null, 4, 5] -> "1,2,#,#,3,4,#,#,5,#,#" -> same treeKey insight
Section titled “Key insight”A list of values alone is ambiguous. 1, 2 could be a left child or a right child. A
traversal becomes reversible once you also record where the nulls are.
Do a preorder walk (node, left, right) and write a marker like # for every missing
child. Then rebuilding is the same walk in reverse: read one token. If it is #, return
null. Otherwise make a node, build its left subtree from the following tokens, then its
right subtree. The tokens are consumed in exactly the order they were written, so no
indices or sizes are needed.
Show solutionHide solution
class Codec: def serialize(self, root: TreeNode | None) -> str: out = []
def dfs(node: TreeNode | None) -> None: if node is None: out.append("#") # null marker pins down the shape return out.append(str(node.val)) dfs(node.left) dfs(node.right)
dfs(root) return ",".join(out)
def deserialize(self, data: str) -> TreeNode | None: tokens = iter(data.split(","))
def build() -> TreeNode | None: token = next(tokens) # consume tokens in the same preorder if token == "#": return None node = TreeNode(int(token)) node.left = build() node.right = build() return node
return build()export class Codec { serialize(root: TreeNode | null): string { const out: string[] = []; function dfs(node: TreeNode | null): void { if (node === null) { out.push('#'); // null marker pins down the shape return; } out.push(String(node.val)); dfs(node.left); dfs(node.right); } dfs(root); return out.join(','); }
deserialize(data: string): TreeNode | null { const tokens = data.split(','); let i = 0; function build(): TreeNode | null { const token = tokens[i++]; // consume tokens in the same preorder if (token === '#') return null; const node = new TreeNode(Number(token)); node.left = build(); node.right = build(); return node; } return build(); }}import java.util.Arrays;import java.util.Iterator;
class Codec { public String serialize(TreeNode root) { StringBuilder out = new StringBuilder(); write(root, out); return out.toString(); }
private void write(TreeNode node, StringBuilder out) { if (node == null) { out.append("#,"); // null marker pins down the shape return; } out.append(node.val).append(','); write(node.left, out); write(node.right, out); }
public TreeNode deserialize(String data) { Iterator<String> tokens = Arrays.asList(data.split(",")).iterator(); return build(tokens); }
private TreeNode build(Iterator<String> tokens) { String token = tokens.next(); // consume tokens in the same preorder if (token.equals("#")) return null; TreeNode node = new TreeNode(Integer.parseInt(token)); node.left = build(tokens); node.right = build(tokens); return node; }}Complexity
Section titled “Complexity”- Time: O(n) — each node and each null marker is written once and read once.
- Space: O(n) — the string holds about 2n tokens, and the recursion stack is O(h), which is O(n) for a skewed tree.
Watch out for
Section titled “Watch out for”- Always write the null markers. A bare preorder cannot distinguish tree shapes. Omitting markers is the most common mistake.
- Pick a delimiter. Without a separator,
1,23and12,3are indistinguishable, and multi-digit and negative numbers break. - Share the token position across recursive calls. Use an iterator or an index that persists, not a copy of the list for each call.
- Empty tree. It serializes to just
#and must come back as null.
Variations
Section titled “Variations”Serialize and Deserialize BST (LeetCode 449)
Section titled “Serialize and Deserialize BST (LeetCode 449)”Same task, but the tree is a BST and the string should be compact. The trick: write plain preorder with no null markers. On decoding, use value bounds, as in Validate BST, to decide where each value belongs.
Construct Binary Tree from Preorder and Inorder Traversal (LeetCode 105)
Section titled “Construct Binary Tree from Preorder and Inorder Traversal (LeetCode 105)”Rebuild a tree from two traversals instead of null markers. The trick: the first preorder value is the root. Find it in inorder to learn the left subtree size, then recurse on both halves. A hash map from value to inorder index makes it O(n).
Find Duplicate Subtrees (LeetCode 652)
Section titled “Find Duplicate Subtrees (LeetCode 652)”Return one root for each group of identical subtrees. The trick: serialize every subtree with this same preorder-with-nulls format and count the strings in a hash map.