Skip to content

Serialize and Deserialize Binary Tree

HardLeetCode #297Time O(n)Space O(n)

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 tree

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()
  • 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.
  • 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,23 and 12,3 are 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.

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).

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.