LeetCode #297 Hard

Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree is LeetCode 297 (Hard). Design a Codec class with two methods:

  • serialize(root) turns a binary tree into a string.
  • deserialize(data) takes a string produced by serialize and rebuilds the tree.

The rebuilt tree must be identical to the original: the same values in the same positions, with every missing child still missing. The string format is entirely up to you, and the two methods must not pass information to each other through member or global variables; the string is the only thing that travels.

The tree has up to 10⁴ nodes with values from -1000 to 1000, so values can be negative or several digits long, and a skewed tree can be 10⁴ levels deep.

Constraints
  • The number of nodes in the tree is in the range [0, 10⁴].
  • -1000 <= Node.val <= 1000
treedfsdesign
Open on LeetCode ↗
02

Intuition

The string must record the shape, not just the values. A plain preorder list cannot: the trees 1 → left 2 and 1 → right 2 both give 1, 2.

The fix is to write a marker for every missing child. Walk the tree in preorder (node, left subtree, right subtree) and write # wherever a child is empty. The two trees now give 1,2,#,#,# and 1,#,2,#,#.

Reading the string back in the same order, each token says what to do:

  • A number: make a node, build its left subtree from the next tokens, then its right.
  • #: this child is empty; return.

One shared cursor into the tokens is all the bookkeeping needed.

How to spot this pattern

Whenever a recursive structure has to be flattened and later rebuilt (saving a tree to disk, sending it over a network, hashing subtrees to find duplicates as in LeetCode 652, or checking whether one tree is a subtree of another by string matching), use one traversal with explicit null markers. The markers are what turn a single traversal into an unambiguous encoding.

03

Approach

Try it first

Before reading on, write the preorder of [1,2] and of [1,null,2] and notice they match. Then add a marker for each missing child and confirm the two strings now differ. Finally, decide how deserialize knows when the left subtree has ended and the right one begins.

1

serialize: preorder with null markers

Run a DFS that, for each call:

  • If the node is null, appends # and returns.
  • Otherwise appends str(node.val), then recurses into the left child, then the right child.

Join the tokens with commas. The comma matters because values like -12 or 1000 have more than one character, so the reader needs a separator to know where each token ends.

2

deserialize: consume tokens in the same order

Split the string on commas and keep an iterator (or an index) over the tokens. A recursive build():

  • Takes the next token.
  • If it is #, returns null.
  • Otherwise creates a node with that value, sets node.left = build(), then node.right = build(), and returns the node.

Call build() once and return its result.

3

Why the left subtree knows where it ends

Every subtree's encoding is complete on its own: each node token is followed by exactly two child encodings, and every path ends in #. So a call to build() consumes precisely the tokens of one subtree and stops; the very next token belongs to the right child. No lengths or brackets are needed.

4

Why the tree rebuilds exactly

By induction on the tree: # encodes the empty tree, and a node encodes as its value followed by the encodings of its left and right subtrees. build() reads a value and then, by the induction hypothesis, rebuilds the left subtree from exactly its tokens and the right subtree from exactly its tokens. So it returns the same tree that was written.

5

Size of the string

A tree with n nodes has n + 1 null children, so the string has 2n + 1 tokens. That is O(n), the best possible, since every value has to be written.

04

Code in Python, C++ and Java

▶1class Codec:
▶2 def serialize(self, root):
▶3 out = []
▶4 
▶5 def dfs(node):
▶6 if not node:
▶7 out.append("#")
▶8 return
▶9 out.append(str(node.val))
▶10 dfs(node.left)
▶11 dfs(node.right)
▶12 
▶13 dfs(root)
▶14 return ",".join(out)
▶15 
▶16 def deserialize(self, data):
▶17 tokens = iter(data.split(","))
▶18 
▶19 def build():
▶20 t = next(tokens)
▶21 if t == "#":
▶22 return None
▶23 node = TreeNode(int(t))
▶24 node.left = build()
▶25 node.right = build()
▶26 return node
▶27 
▶28 return build()
serialize12345string1writewrite 1
node1depth 0
out1 of 11tokens written
Serialize in preorder: write a node, then its left subtree, then its right. Every missing child is written as #, so the 11 slots (5 values + 6 markers) fill exactly once. The root goes first.
serialize12345string12writewrite 2
node2depth 1
out2 of 11tokens written
Write 2 before visiting its children. It has no children, so its left call and its right call will each write #.
serialize12345#string12#writeleft of 2 is empty → #
childleft of 2is null
out3 of 11tokens written
The left child of 2 is missing, so write # in its place. Plain preorder would drop this gap; the marker tells a reader that the next value is not 2's left child.
serialize12345##string12##writeright of 2 is empty → #
childright of 2is null
out4 of 11tokens written
The right child of 2 is missing, so write # in its place. That closes 2's subtree: both of its children are now recorded.
serialize12345##string12##3writewrite 3
node3depth 1
out5 of 11tokens written
Write 3 before visiting its children. Its left subtree comes next, then its right.
serialize12345##string12##34writewrite 4
node4depth 2
out6 of 11tokens written
Write 4 before visiting its children. It has no children, so its left call and its right call will each write #.
serialize12345###string12##34#writeleft of 4 is empty → #
childleft of 4is null
out7 of 11tokens written
The left child of 4 is missing, so write # in its place. Plain preorder would drop this gap; the marker tells a reader that the next value is not 4's left child.
serialize12345####string12##34##writeright of 4 is empty → #
childright of 4is null
out8 of 11tokens written
The right child of 4 is missing, so write # in its place. That closes 4's subtree: both of its children are now recorded.
serialize12345####string12##34##5writewrite 5
node5depth 2
out9 of 11tokens written
Write 5 before visiting its children. It has no children, so its left call and its right call will each write #.
serialize12345#####string12##34##5#writeleft of 5 is empty → #
childleft of 5is null
out10 of 11tokens written
The left child of 5 is missing, so write # in its place. Plain preorder would drop this gap; the marker tells a reader that the next value is not 5's left child.
serialize12345######string12##34##5##writeright of 5 is empty → #
childright of 5is null
out11 of 11tokens written
The right child of 5 is missing, so write # in its place. That closes 5's subtree: both of its children are now recorded.
serialize12345######string12##34##5##join with commas → one string
serialize"1,2,#,#,3,4,#,#,5,#,#"
Join with commas: "1,2,#,#,3,4,#,#,5,#,#". The comma is needed because tokens like -3 or 10 are more than one character. This string is the only thing passed to deserialize. Without the markers it would be just 1,2,3,4,5, which other tree shapes produce too.
deserialize1string12##34##5##readread 1 → root
token"1"a value
attachroot
Deserialize in the same preorder. The first token is the root, because preorder wrote it first. Create node 1; the tokens that follow encode its left subtree, then its right.
deserialize12string12##34##5##readread 2 → left of 1
token"2"a value
attachleft of 1
2 is a value, so create a node and attach it as the left child of 1. Recursion continues into this node's own left child.
deserialize12#string12##34##5##readread # → left of 2 is empty
token"#"null child
node2has no left child
# means 2's left child is empty, so this call returns null. The next token therefore belongs to 2's right child.
deserialize12##string12##34##5##readread # → right of 2 is empty
token"#"null child
node2has no right child
# means 2's right child is empty, so this call returns null. That completes 2's subtree, and control returns to its parent.
deserialize123##string12##34##5##readread 3 → right of 1
token"3"a value
attachright of 1
3 is a value, so create a node and attach it as the right child of 1. The right call starts here because the left subtree of 1 already used up all of its tokens, ending on a #.
deserialize1234##string12##34##5##readread 4 → left of 3
token"4"a value
attachleft of 3
4 is a value, so create a node and attach it as the left child of 3. Recursion continues into this node's own left child.
deserialize1234###string12##34##5##readread # → left of 4 is empty
token"#"null child
node4has no left child
# means 4's left child is empty, so this call returns null. The next token therefore belongs to 4's right child.
deserialize1234####string12##34##5##readread # → right of 4 is empty
token"#"null child
node4has no right child
# means 4's right child is empty, so this call returns null. That completes 4's subtree, and control returns to its parent.
deserialize12345####string12##34##5##readread 5 → right of 3
token"5"a value
attachright of 3
5 is a value, so create a node and attach it as the right child of 3. The right call starts here because the left subtree of 3 already used up all of its tokens, ending on a #.
deserialize12345#####string12##34##5##readread # → left of 5 is empty
token"#"null child
node5has no left child
# means 5's left child is empty, so this call returns null. The next token therefore belongs to 5's right child.
deserialize12345######string12##34##5##last # read → tree rebuilt
token"#"null child
tokens read11 of 11string used up
# is 5's empty right child. That closes the last open child, so the recursion ends exactly at the end of the string. Every token was used once, and the rebuilt tree has the same values in the same places as the original.
05

Level-order BFS version

serialize pops nodes from a queue, writing each value or #, and pushes both children of every real node. deserialize reads the root, then hands each popped node the next two tokens as its left and right child.

▶1class Codec:
▶2 def serialize(self, root):
▶3 out = []
▶4 q = deque([root])
▶5 while q:
▶6 node = q.popleft()
▶7 if not node:
▶8 out.append("#")
▶9 continue
▶10 out.append(str(node.val))
▶11 q.append(node.left)
▶12 q.append(node.right)
▶13 return ",".join(out)
▶14 
▶15 def deserialize(self, data):
▶16 tokens = data.split(",")
▶17 if tokens[0] == "#":
▶18 return None
▶19 root = TreeNode(int(tokens[0]))
▶20 q = deque([root])
▶21 i = 1
▶22 while q:
▶23 node = q.popleft()
▶24 if tokens[i] != "#":
▶25 node.left = TreeNode(int(tokens[i]))
▶26 q.append(node.left)
▶27 i += 1
▶28 if tokens[i] != "#":
▶29 node.right = TreeNode(int(tokens[i]))
▶30 q.append(node.right)
▶31 i += 1
▶32 return root
06

Common pitfalls

Skipping the null markers

✗ Wrong
if not node:
    return
✓ Right
if not node:
    out.append("#")
    return

Without markers, [1,2] and [1,null,2] both serialize to 1,2, so deserialize cannot know whether 2 is a left or a right child. The markers are the shape information.

Concatenating values without a separator

✗ Wrong
return "".join(out)
✓ Right
return ",".join(out)

With values like 12 and -3, the string 12-3 could be read as 1, 2, -3. A delimiter makes each token's boundary explicit.

Restarting the token cursor in each recursive call

✗ Wrong
def build(tokens, i):
    ...
    node.left = build(tokens, i + 1)
    node.right = build(tokens, i + 2)
✓ Right
tokens = iter(data.split(","))
# every build() call pulls from the same iterator

The right subtree starts after the whole left subtree, not one token later. Only a cursor shared by all calls (an iterator, a deque, or an index passed by reference) knows how many tokens the left subtree used.

Keeping the tree in a class field

✗ Wrong
def serialize(self, root):
    self.saved = root
    return "x"
✓ Right
def serialize(self, root):
    ...
    return ",".join(out)

The problem forbids passing state through member or global variables. The string must carry everything, so the encoding has to be complete on its own.

07

Edge cases

Empty tree

serialize(None) writes a single #, and deserialize("#") reads it and returns None. No special case is needed in either method.

Negative and multi-digit values

Values range from -1000 to 1000. str() and int() handle the sign and length, and the comma separator keeps tokens apart.

Skewed tree of 10⁴ nodes

Both recursions go 10⁴ levels deep. A recursive Python solution hits the default limit of 1000, so raise it with sys.setrecursionlimit or use the level-order code below, which has no recursion. C++ and Java handle this depth with LeetCode's default stacks.

08

Complexity

Time
O(n)
Space
O(n)
Each node is written once and read once, and the string holds 2n + 1 tokens. The recursion stack is O(h), the height of the tree, which is O(n) for a skewed tree.
09

Serialize and Deserialize Binary Tree FAQ

How do you solve this problem?
  • Serialize: preorder DFS; write each value, and write # for every missing child. Join with commas.
  • Deserialize: split on commas; recursively take the next token, return null for #, otherwise create a node and build its left then right subtree from the following tokens.
  • Complexity: O(n) time and space, with a 2n + 1 token string.
Why can't preorder alone rebuild a binary tree?

Preorder records the order of values but not where the gaps are. Different shapes can give the same sequence, so a second traversal (usually inorder) is needed. Recording the gaps as # markers puts the missing information back into a single traversal.

Is this the same as LeetCode 449, Serialize and Deserialize BST?

This code works for 449 too, but a BST allows a shorter string: the preorder values alone are enough, because the BST ordering tells you where the left subtree ends (the first value larger than the root). No null markers are needed there.