297. Serialize and Deserialize Binary Tree
At a Glance
- Topic: String
- Pattern: Analyze Pattern
- Difficulty: Hard
- LeetCode: 297
Problem Statement
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Example 1:
Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5]
Example 2:
Input: root = [] Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <=...Approach & Solution Steps
Use Preorder Traversal (DFS). Serialize to a string using commas to separate values, and use 'N' for null nodes. For deserialization, split the string by comma and use a recursive function with a queue to rebuild the tree.
Optimal JS Solution
var serialize = function(root) {
const res = [];
function dfs(node) {
if (!node) {
res.push('N');
return;
}
res.push(node.val);
dfs(node.left);
dfs(node.right);
}
dfs(root);
return res.join(',');
};
var deserialize = function(data) {
const vals = data.split(',');
let i = 0;
function dfs() {
if (vals[i] === 'N') {
i++;
return null;
}
const node = new TreeNode(Number(vals[i]));
i++;
node.left = dfs();
node.right = dfs();
return node;
}
return dfs();
};Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?