Serialize and Deserialize Binary Tree
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Design a way to turn a binary tree into a string and back.
serialize(root)returns a string.deserialize(data)takes that string and returns a tree with the same structure and values as the original.
Understand the problem
- Serializing means turning a data structure into text (or bytes) so it can be saved to a file or sent over a network. Deserializing is the reverse: rebuilding the structure from the text. JSON is a familiar example.
- The format is up to you. The only requirement:
deserialize(serialize(tree))gives back an identical tree (same shape, same values). - Your functions can't cheat by storing the tree in a global variable: the string must contain everything.
Example 1
Input: root = [1, 2, 3, null, null, 4, 5]
Output: [1, 2, 3, null, null, 4, 5]
1
/ \
2 3
/ \
4 5The tests run deserialize(serialize(root)) and expect the same tree back.
Example 2
Input: root = []
Output: []An empty tree must survive the round trip too.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.
Constraints
0 <= number of nodes <= 10^4-1000 <= Node.val <= 1000- Your functions must not keep state between calls (no global caches).
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Write the tree in preorder (node, left, right) with a # for every missing child; to rebuild it, read the tokens back with the same recursion in the same order.
Why the values alone aren't enough
If you write only the values in preorder, these two different trees give the same string 1,2:
1 1
/ \
2 2The shape is lost. The fix: also write down every missing child, with a marker like #:
left tree: 1,2,#,#,#
right tree: 1,#,2,#,#Now they're different. With the gaps recorded, one string means exactly one tree.
The key insight
Use the same recursion in both directions:
- Serialize (write): at each node, write its value, then write its left subtree, then its right subtree. For an empty spot, write
#. - Deserialize (read): take the next token. If it's
#, this spot is empty: returnnull. Otherwise create the node, then read its left subtree, then read its right subtree.
Because reading follows exactly the order of writing, each recursive call uses up exactly the tokens its subtree wrote. No counting or indexes needed.
Step by step
The tree from the example serializes to:
1,2,#,#,3,4,#,#,5,#,#Reading it back (the arrow shows the token being read):
| Token | Meaning |
|---|---|
1 | create root 1, now read its left |
2 | create 2 as 1's left, read its left |
# | 2 has no left child |
# | 2 has no right child → back to 1's right |
3 | create 3 as 1's right, read its left |
4 | create 4 as 3's left |
#, # | 4 has no children → back to 3's right |
5 | create 5 as 3's right |
#, # | 5 has no children. Done! |
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n) for both functions. Each node (and each empty spot) is written and read once.
- Memory: O(n) for the string, plus O(h) for the recursion.
Common mistakes
- No null markers. Then different trees produce the same string, as shown above.
- No separators.
12and1,2would look the same. Join tokens with commas (or another character that can't appear in a value). - Reading in a different order from writing. Preorder in, preorder out.
- Forgetting the empty tree. It serializes to just
#, and deserializing#must givenull.
Going deeper
- Level order (BFS) works too: write the tree level by level with
nullmarkers, exactly like the test format. To rebuild it, use a queue: each node read takes the next two tokens as its left and right children. It also avoids deep recursion on very lopsided trees. - Real systems (JSON, Protocol Buffers) solve the same problem: turning nested structures into flat text and back without losing the shape.
Reference solution
/**
* @param {TreeNode | null} root
* @return {string}
*/
export function serialize(root) {
const tokens = []
// Preorder: the node, then its left subtree, then its right subtree.
function write(node) {
if (!node) {
tokens.push('#') // mark the empty spot, so the shape is kept
return
}
tokens.push(String(node.val))
write(node.left)
write(node.right)
}
write(root)
return tokens.join(',') // commas keep "12" and "1,2" apart
}
/**
* @param {string} data
* @return {TreeNode | null}
*/
export function deserialize(data) {
const tokens = data.split(',')
let next = 0 // the next token to read
// Read in EXACTLY the order serialize wrote: node, left subtree, right subtree.
function read() {
const token = tokens[next++]
if (token === '#') return null // an empty spot
const node = new TreeNode(Number(token))
node.left = read() // uses up exactly the tokens the left subtree wrote
node.right = read()
return node
}
return read()
}export function serialize(root: TreeNode | null): string {
const tokens: string[] = []
// Preorder: the node, then its left subtree, then its right subtree.
function write(node: TreeNode | null): void {
if (!node) {
tokens.push('#') // mark the empty spot, so the shape is kept
return
}
tokens.push(String(node.val))
write(node.left)
write(node.right)
}
write(root)
return tokens.join(',') // commas keep "12" and "1,2" apart
}
export function deserialize(data: string): TreeNode | null {
const tokens = data.split(',')
let next = 0 // the next token to read
// Read in EXACTLY the order serialize wrote: node, left subtree, right subtree.
function read(): TreeNode | null {
const token = tokens[next++]
if (token === '#') return null // an empty spot
const node = new TreeNode(Number(token))
node.left = read() // uses up exactly the tokens the left subtree wrote
node.right = read()
return node
}
return read()
}def serialize(root: TreeNode | None) -> str:
tokens = []
# Preorder: the node, then its left subtree, then its right subtree.
def write(node: TreeNode | None) -> None:
if node is None:
tokens.append("#") # mark the empty spot, so the shape is kept
return
tokens.append(str(node.val))
write(node.left)
write(node.right)
write(root)
return ",".join(tokens) # commas keep "12" and "1,2" apart
def deserialize(data: str) -> TreeNode | None:
tokens = iter(data.split(",")) # next(tokens) gives the next token to read
# Read in EXACTLY the order serialize wrote: node, left subtree, right subtree.
def read() -> TreeNode | None:
token = next(tokens)
if token == "#":
return None # an empty spot
node = TreeNode(int(token))
node.left = read() # uses up exactly the tokens the left subtree wrote
node.right = read()
return node
return read()