You can do in this in many ways, the following code does this using prefix traversal.
/**
* @param {Node} root
* @return {string}
*/
function serialize(root) {
if(!root) return '_';
return `${root.val},${serialize(root.left)},${serialize(root.right)}`;
}
/**
* @param {string} str
* @return {Node}
*/
function deserialize(str) {
const q = str.split(',');
return dfs(q);
/**
* @param {string} str
* @return {Node}
*/
function dfs(que) {
if(!que.length) return null;
const n = que.shift()
;
if(n !== '_') {
const node = new Node(n.value)
node.left = dfs(q);
node.right = dfs(q);
return node;
}
return null;
}
}