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 byserializeand 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.
- The number of nodes in the tree is in the range [0, 10⁴].
- -1000 <= Node.val <= 1000
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.
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.
Approach
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.
Two ways to solve it
Write each node, then its left and right subtrees, with # for every missing child. Read the tokens back in the same order.
- Code: two short recursive functions.
- Rebuild: one shared cursor, no index maths.
- Limit: recursion as deep as the tree.
The shortest version to write and explain.
Write the tree level by level, # for each missing child. To rebuild, give each queued node the next two tokens as its children.
- Format: close to LeetCode's own
[1,2,3,null,null,4,5]. - Stack: no recursion, so no depth limit.
- Cost: a little more code in both methods.
Useful when the tree may be very deep.
Both run in O(n) and both depend on null markers; the preorder version is shorter because the recursion itself tracks where each subtree ends. The steps, code and live demo below follow the preorder version; the level-order code comes after the demo.
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.
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(), thennode.right = build(), and returns the node.
Call build() once and return its result.
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.
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.
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.
Code in Python, C++ and Java
deserialize. Without the markers it would be just 1,2,3,4,5, which other tree shapes produce too.deserialize. Without the markers it would be just 1,2, which other tree shapes produce too.deserialize. Without the markers it would be just 10,-3, which other tree shapes produce too.dfs(None) writes # and returns. The string still says something: one marker means "no tree".deserialize.build() returns null at once. An empty tree round-trips with no special case in either method.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.
Common pitfalls
Skipping the null markers
if not node:
returnif not node:
out.append("#")
returnWithout 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
return "".join(out)
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
def build(tokens, i):
...
node.left = build(tokens, i + 1)
node.right = build(tokens, i + 2)tokens = iter(data.split(","))
# every build() call pulls from the same iteratorThe 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
def serialize(self, root):
self.saved = root
return "x"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.
Edge cases
serialize(None) writes a single #, and deserialize("#") reads it and returns None. No special case is needed in either method.
Values range from -1000 to 1000. str() and int() handle the sign and length, and the comma separator keeps tokens apart.
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.
Complexity
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.