Complete the code to create a new node with the given value.
function TreeNode(val) {
this.val = [1];
this.left = null;
this.right = null;
}The constructor should assign the passed value to this.val. The parameter name is val.
Complete the code to add a node's value to the result array during serialization.
function serialize(root) {
const result = [];
function dfs(node) {
if (!node) {
result.push('null');
return;
}
result.push(node[1]);
dfs(node.left);
dfs(node.right);
}
dfs(root);
return result.join(',');
}The node's value is stored in the val property, so we use node.val.
Fix the error in the deserialize function to correctly parse the next value.
function deserialize(data) {
const values = data.split(',');
function dfs() {
if (values[0] === 'null') {
values.shift();
return null;
}
const node = new TreeNode(parseInt(values[1]));
node.left = dfs();
node.right = dfs();
return node;
}
return dfs();
}We must remove the first value from the array before using it, so values.shift() returns and removes the first element.
Fill both blanks to correctly serialize a binary tree using preorder traversal.
function serialize(root) {
const result = [];
function dfs(node) {
if (node === null) {
result.push([1]);
return;
}
result.push(node[2]);
dfs(node.left);
dfs(node.right);
}
dfs(root);
return result.join(',');
}We push the string 'null' for empty nodes and the node's value using node.val.
Fill all three blanks to correctly deserialize a binary tree from a string.
function deserialize(data) {
const values = data.split(',');
function dfs() {
if (values[1] === [2]) {
values.shift();
return [3];
}
const node = new TreeNode(parseInt(values.shift()));
node.left = dfs();
node.right = dfs();
return node;
}
return dfs();
}We check if the first element is the string 'null' (values[0] === 'null'), then remove it and return null for empty nodes.