Serialize and Deserialize Binary Tree
Hard · Trees
Jump to codeCreate a representation of a binary tree that can reconstruct both its values and exact shape. Support empty trees and negative values.
Examples
Example 1
root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Example 2
root = []
Output: []
Constraints
- 0 <= The number of nodes in the tree <= 1000
- -1000 <= Node.val <= 1000
Function contract
Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.
Implement serialize(root) and deserialize(data). The grader serializes a tree, deserializes that string, and compares the recovered tree. Any unambiguous encoding is accepted.
Need a hint?
Values alone cannot distinguish different shapes.
Real tree interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Lowest Common Manager of a Group of Employees in an Org ChartAmazon
- Repeatedly Delete Leaves Matching a Target Value From a Binary TreeGoogle
- Merge two N-ary trees by key rulesLinkedIn
Solution approach
Serialize in preorder, writing an explicit null marker for every absent child. Deserialize by consuming tokens once: a null marker returns null; a value creates a node whose left and right subtrees are recursively read next. Delimit values unambiguously and use a token list to avoid repeated string concatenation.
Complexity
O(n) tokens and O(n) space; character cost also includes the length of encoded values.
Python reference solution
def serialize(root):
tokens = []
def visit(node):
if node is None:
tokens.append('#')
else:
tokens.append(str(node.val))
visit(node.left)
visit(node.right)
visit(root)
return ','.join(tokens)
def deserialize(data):
tokens = iter(data.split(','))
def build():
value = next(tokens)
if value == '#':
return None
node = TreeNode(int(value))
node.left, node.right = build(), build()
return node
return build()
JavaScript solution
function serialize(root) {
const tokens = [];
function visit(node) {
if (!node) { tokens.push('#'); return; }
tokens.push(String(node.val));
visit(node.left);
visit(node.right);
}
visit(root);
return tokens.join(',');
}
function deserialize(data) {
const tokens = data.split(',');
let cursor = 0;
function build() {
const token = tokens[cursor++];
if (token === '#') return null;
const node = new TreeNode(Number(token));
node.left = build();
node.right = build();
return node;
}
return build();
}
Java solution
import java.util.*;
class Solution {
public String serialize(TreeNode root) {
StringBuilder data = new StringBuilder();
visit(root, data);
return data.toString();
}
private void visit(TreeNode node, StringBuilder data) {
if (node == null) { data.append("#,"); return; }
data.append(node.val).append(',');
visit(node.left, data);
visit(node.right, data);
}
public TreeNode deserialize(String data) {
return build(data.split(","), new int[]{0});
}
private TreeNode build(String[] tokens, int[] cursor) {
String token = tokens[cursor[0]++];
if (token.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(token));
node.left = build(tokens, cursor);
node.right = build(tokens, cursor);
return node;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
void visit(TreeNode* node, string& data) {
if (!node) { data += "#,"; return; }
data += to_string(node->val) + ",";
visit(node->left, data);
visit(node->right, data);
}
TreeNode* build(istringstream& data) {
string token;
getline(data, token, ',');
if (token == "#") return nullptr;
TreeNode* node = new TreeNode(stoi(token));
node->left = build(data);
node->right = build(data);
return node;
}
public:
string serialize(TreeNode* root) {
string data;
visit(root, data);
return data;
}
TreeNode* deserialize(string data) {
istringstream tokens(data);
return build(tokens);
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
2,
3,
null,
null,
4,
5
]
][ 1, 2, 3, null, null, 4, 5 ]
[ [] ]
[]
[
[
1
]
][ 1 ]
[
[
1,
2,
null,
3
]
][ 1, 2, null, 3 ]
[
[
1,
null,
2,
null,
3
]
][ 1, null, 2, null, 3 ]
Drafts are saved per language in this browser when storage is available.