297. Serialize and Deserialize Binary Tree
Hard NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Trees
- Time
- O(n)
- Space
- O(n)
Standard Solution (C++)
SummaryConvert a binary tree into a string and reconstruct an identical tree from that string, supporting any structure including empty subtrees.
Approach
Use a preorder traversal that emits a marker for null children.
- Serialize: write each node's value followed by recursive calls on left and right; emit a sentinel such as 'N' for a missing node, separating tokens with spaces.
- Deserialize: read tokens in the same preorder sequence; a sentinel produces a null node, otherwise build a node and recursively construct its left then right subtrees.
class Codec {
public:
string serialize(TreeNode* root) {
string result;
function<void(TreeNode*)> dfs = [&](TreeNode* node) {
if (!node) {
result += "N ";
return;
}
result += to_string(node->val) + " ";
dfs(node->left);
dfs(node->right);
};
dfs(root);
return result;
}
TreeNode* deserialize(string data) {
istringstream in(data);
function<TreeNode*()> build = [&]() -> TreeNode* {
string token;
in >> token;
if (token == "N") return nullptr;
TreeNode* node = new TreeNode(stoi(token));
node->left = build();
node->right = build();
return node;
};
return build();
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground C++
Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.
C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.