Source: https://bigfrontend.dev/problem/serialize-and-deserialize-binary-tree

function serialize(root) {
// Recursive DFS approach
function dfsSerialize(root) {
// If the root exists, we push the current value of the root and recursively go through the left and right children
if (root) {
result.push(root.value);
dfsSerialize(root.left);
dfsSerialize(root.right);
} else {
// If the root is null, we push null onto the array
result.push("null");
}
}
// Manage a result with closure that we'll append the nodes to
const result = [];
dfsSerialize(root);
return result.toString();
}
function deserialize(str) {
// We can do a recursive DFS to deserialize the serialized tree
function dfsDeserialize() {
// Get the current value from nodes and increment onto the next node
const currentValue = nodes[i++];
// If the current node is null, return null
if (currentValue === "null") {
return null;
}
// Otherwise, create a node based on the value and recursively assign the left and right of the current node
const node = new Node(+currentValue);
node.left = dfsDeserialize();
node.right = dfsDeserialize();
return node;
}
// Split the serialized tree by commas to get the nodes
const nodes = str.split(",");
// Start from the root node index at 0
let i = 0;
return dfsDeserialize();
}