Home
DSA Patterns
Depth-First Search
Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree (LeetCode 297)
Serialize and Deserialize Binary Tree (LeetCode 297): turn a binary tree into a string and back with a preorder DFS that writes a marker for every empty child.
Problem Understanding
Serialize and Deserialize Binary Tree: design two functions. serialize turns a binary tree into a string, and deserialize turns that string back into the same tree. The format is up to you; it only has to round-trip.
Example: the tree [1, 2, 3, null, null, 4, 5] serializes, with the method below, to "1,2,#,#,3,4,#,#,5,#,#".
The Intuition: Preorder Plus Null Markers
Preorder (node, left, right) is a natural way to write a tree down, but values alone lose the shape. The fix is to write a marker, #, for every empty child as well. Then:
- Serialize: visit a node, write its value, recurse left, recurse right. An empty child writes
#. - Deserialize: read the tokens back in the same order. A value creates a node; its left child is built from the next tokens, then its right child. A
#returns an empty child.
Because both directions use the same order, each call to build reads exactly the tokens of its own subtree.
Serialize and Deserialize Binary Tree Visualization
PREORDER, '#' FOR EVERY EMPTY CHILD
SERIALIZE: WRITE VALUE
Phase
write
Tokens
1
Written
1
string so far
Visit 1: write its value, then its left subtree, then its right
Next
Visit 2: write its value, then its left subtree, then its right
Tree
First the tree is serialized: nodes fill in as preorder writes them, and the token list grows with a # for each empty child. Then the tree is cleared and rebuilt from those tokens, with the token being read marked and each node reappearing where it came from.
Serialize and Deserialize Binary Tree Dry Run
Deserialize: "1,2,#,#,3,4,#,#,5,#,#"
| Token | Action |
|---|---|
| 1 | create 1, build its left |
| 2 | create 2 as 1's left, build its left |
| # | 2 has no left child |
| # | 2 has no right child; 2 is complete |
| 3 | create 3 as 1's right, build its left |
| 4 | create 4 as 3's left; its two #s follow |
| 5 | create 5 as 3's right; its two #s end the string |
Serialize and Deserialize Binary Tree LeetCode Solution
Preorder DFS with '#' markers, and a recursive rebuild that reads the tokens in the same order.
Serialize and Deserialize Binary Tree Code
1var serialize = function(root) {2 const out = [];3 const dfs = (node) => {4 if (!node) {5 out.push('#');6 return;7 }8 out.push(String(node.val));9 dfs(node.left);10 dfs(node.right);11 };12 dfs(root);13 return out.join(',');14};1516var deserialize = function(data) {17 const tokens = data.split(',');18 let i = 0;19 const build = () => {20 const token = tokens[i++];21 if (token === '#') return null;22 const node = new TreeNode(Number(token));23 node.left = build();24 node.right = build();25 return node;26 };27 return build();28};
Serialize and Deserialize Binary Tree in Python, Java, C++, TypeScript and C
Serialize and Deserialize Binary Tree in Python
class Codec:
def serialize(self, root):
out = []
def dfs(node):
if not node:
out.append('#')
return
out.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(out)
def deserialize(self, data):
tokens = iter(data.split(','))
def build():
token = next(tokens)
if token == '#':
return None
node = TreeNode(int(token))
node.left = build()
node.right = build()
return node
return build()Serialize and Deserialize Binary Tree in Java
public class Codec {
public String serialize(TreeNode root) {
StringBuilder out = new StringBuilder();
dfs(root, out);
return out.substring(0, out.length() - 1);
}
private void dfs(TreeNode node, StringBuilder out) {
if (node == null) {
out.append("#,");
return;
}
out.append(node.val).append(',');
dfs(node.left, out);
dfs(node.right, out);
}
public TreeNode deserialize(String data) {
Deque<String> tokens = new ArrayDeque<>(Arrays.asList(data.split(",")));
return build(tokens);
}
private TreeNode build(Deque<String> tokens) {
String token = tokens.poll();
if (token.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(token));
node.left = build(tokens);
node.right = build(tokens);
return node;
}
}Serialize and Deserialize Binary Tree in C++
class Codec {
public:
string serialize(TreeNode* root) {
string out;
dfs(root, out);
out.pop_back();
return out;
}
TreeNode* deserialize(string data) {
istringstream in(data);
return build(in);
}
private:
void dfs(TreeNode* node, string& out) {
if (!node) {
out += "#,";
return;
}
out += to_string(node->val) + ",";
dfs(node->left, out);
dfs(node->right, out);
}
TreeNode* build(istringstream& in) {
string token;
getline(in, token, ',');
if (token == "#") return nullptr;
TreeNode* node = new TreeNode(stoi(token));
node->left = build(in);
node->right = build(in);
return node;
}
};Serialize and Deserialize Binary Tree in TypeScript
function serialize(root: TreeNode | null): string {
const out: string[] = [];
const dfs = (node: TreeNode | null): void => {
if (!node) {
out.push('#');
return;
}
out.push(String(node.val));
dfs(node.left);
dfs(node.right);
};
dfs(root);
return out.join(',');
}
function deserialize(data: string): TreeNode | null {
const tokens = data.split(',');
let i = 0;
const build = (): TreeNode | null => {
const token = tokens[i++];
if (token === '#') return null;
const node = new TreeNode(Number(token));
node.left = build();
node.right = build();
return node;
};
return build();
}Serialize and Deserialize Binary Tree in C
static void dfs(struct TreeNode* node, char* out, int* len) {
if (!node) {
*len += sprintf(out + *len, "#,");
return;
}
*len += sprintf(out + *len, "%d,", node->val);
dfs(node->left, out, len);
dfs(node->right, out, len);
}
char* serialize(struct TreeNode* root) {
char* out = malloc(200000);
int len = 0;
dfs(root, out, &len);
out[len - 1] = '\0';
return out;
}
static struct TreeNode* build(char** cursor) {
char* token = strsep(cursor, ",");
if (token[0] == '#') return NULL;
struct TreeNode* node = malloc(sizeof(struct TreeNode));
node->val = atoi(token);
node->left = build(cursor);
node->right = build(cursor);
return node;
}
struct TreeNode* deserialize(char* data) {
char* cursor = data;
return build(&cursor);
}Edge Cases & Common Mistakes
- Empty tree: serializes to
"#"and deserializes back tonull. - Negative and multi-digit values: a delimiter between tokens keeps
-12from being read as-1and2. - Dropping the markers: without
#, different trees produce the same string and the rebuild guesses wrong. - Using
str.splitandindexOfrepeatedly: re-scanning the string for each node makes deserialize O(n²); keep one cursor.
Summary
Preorder plus a marker for every empty child is a complete description of a binary tree. Serialize writes it with one DFS, and deserialize reads it back with a DFS in the same order, each call consuming exactly its own subtree's tokens. Both run in O(n).
More practice: DSA interview questions with answers · patterns cheat sheet
