Overview
Design an algorithm to serialize a binary tree into a string and deserialize that string back into the original tree. The serialization format is up to you — the only requirement is that deserialize(serialize(root)) produces a structurally identical tree.
Constraints
- The tree can have 0 to 5,000 nodes.
- Node values are integers in range
[-1000, 1000]. serializemust return a string.deserializemust accept that string and return the root node.nullroot should serialize and deserialize correctly.
Examples
// Tree:
// 1
// / \
// 2 3
// / \
// 4 5
const tree = { val: 1, left: { val: 2, left: null, right: null }, right: { val: 3, left: { val: 4, left: null, right: null }, right: { val: 5, left: null, right: null } } };
const str = serialize(tree);
deserialize(str);
// => structurally identical treeserialize(null); // some string representation deserialize(serialize(null)); // => null
Solution
Reveal solution
function serialize(root) {
const parts = [];
function dfs(node) {
if (node === null) { parts.push("N"); return; }
parts.push(String(node.val));
dfs(node.left);
dfs(node.right);
}
dfs(root);
return parts.join(",");
}
function deserialize(data) {
const tokens = data.split(",");
let i = 0;
function dfs() {
if (tokens[i] === "N") { i++; return null; }
const node = { val: Number(tokens[i]), left: null, right: null };
i++;
node.left = dfs();
node.right = dfs();
return node;
}
return dfs();
}Resources
binary-tree-serialization.js
Binary Tree Serialization and Deserialization
hardcodingAlgorithmsTrees
Overview
Design an algorithm to serialize a binary tree into a string and deserialize that string back into the original tree. The serialization format is up to you — the only requirement is that deserialize(serialize(root)) produces a structurally identical tree.
Constraints
- The tree can have 0 to 5,000 nodes.
- Node values are integers in range
[-1000, 1000]. serializemust return a string.deserializemust accept that string and return the root node.nullroot should serialize and deserialize correctly.
Examples
// Tree:
// 1
// / \
// 2 3
// / \
// 4 5
const tree = { val: 1, left: { val: 2, left: null, right: null }, right: { val: 3, left: { val: 4, left: null, right: null }, right: { val: 5, left: null, right: null } } };
const str = serialize(tree);
deserialize(str);
// => structurally identical treeserialize(null); // some string representation deserialize(serialize(null)); // => null
Solution
Reveal solution
function serialize(root) {
const parts = [];
function dfs(node) {
if (node === null) { parts.push("N"); return; }
parts.push(String(node.val));
dfs(node.left);
dfs(node.right);
}
dfs(root);
return parts.join(",");
}
function deserialize(data) {
const tokens = data.split(",");
let i = 0;
function dfs() {
if (tokens[i] === "N") { i++; return null; }
const node = { val: Number(tokens[i]), left: null, right: null };
i++;
node.left = dfs();
node.right = dfs();
return node;
}
return dfs();
}Resources
NameTopicDifficulty
103 of 103 problems