Serialize and Deserialize Binary Tree Hard 0 attempts
LeetCode ↗

Serialize and Deserialize Binary Tree

Hard TreeBinary TreeDFS LeetCode

Design an algorithm to serialize a binary tree to a string and deserialize the string back to a tree.

Example: root = [1,2,3,null,null,4,5] → "1,2,null,null,3,4,null,null,5,null,null"

Sample Input
Sample Output
Constraints
  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000

Preorder with null markers

function serialize(root) {
  const result = [];
  function dfs(node) {
    if (!node) { result.push('null'); return; }
    result.push(node.val);
    dfs(node.left); dfs(node.right);
  }
  dfs(root);
  return result.join(',');
}
function deserialize(data) {
  const vals = data.split(',');
  let i = 0;
  function build() {
    if (vals[i] === 'null') { i++; return null; }
    const node = {val: Number(vals[i++]), left: null, right: null};
    node.left = build(); node.right = build();
    return node;
  }
  return build();
}

Time: O(n) | Space: O(n)

Saved in this browser only. Private to you.

JavaScript