This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
110. serialize and deserialize binary tree

Solution:

To serialize a binary tree, we can use a preorder traversal approach. We add the value of the current node to the string and separate them with commas. If a node is null, we add "null" to the string. After that, we recursively serialize the left subtree and then the right subtree.

To deserialize the string back into a binary tree, we can use a queue to keep track of the nodes in the string. We split the string into an array and initialize the queue with it. Then we recursively build the tree by dequeuing the first value in the queue and creating a node with it. If the value is null, we return null. Otherwise, we recursively set the left and right children of the current node to the values dequeued from the queue.

Here's the implementation:

function serialize(root) {
  if (!root) {
    return "null";
  }
  const left = serialize(root.left);
  const right = serialize(root.right);
  return `${root.val},${left},${right}`;
}

function deserialize(str) {
  const values = str.split(",");
  const queue = values.reverse();
  return buildTree(queue);

  function buildTree(queue) {
    const val = queue.pop();
    if (val === "null") {
      return null;
    }
    const node = new Node(parseInt(val));
    node.left = buildTree(queue);
    node.right = buildTree(queue);
    return node;
  }
}