Skip to problem
←

Serialize and Deserialize Binary Tree

Hard 0 attempts

Implement two functions that encode a binary tree into a string and reconstruct its values and shape:

  • serialize(root) returns a string. Use any unambiguous encoding you choose.
  • deserialize(data) returns a newly constructed tree from that string.

The functions run in separate fresh scopes. Do not rely on shared variables or saved node references: the string must contain everything needed to reconstruct the tree. The empty tree must also round-trip correctly.

Missing children matter. For example, [1,2] (a left child) and [1,null,2] (a right child) must have distinguishable encodings. Node values can repeat or be negative.

The result shown by the runner is the reconstructed tree, not the encoded string. The displayed level-order array is only the input/output notation; you do not have to use it as your string format.

Function contract

Implement serialize(root) and deserialize(data). The runner calls them in separate fresh scopes, so the encoded string must contain all information needed to rebuild the tree. Trees are shown as level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: serialize must return a string in any format you choose. deserialize must return a new tree with the same values and structure. The reconstructed tree is displayed as a level-order array with trailing nulls removed.

Example 1

Input
root = [1,2,3,null,null,4,5]
Output
[1,2,3,null,null,4,5]

Example 2

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

Iterative Preorder with Null Markers

Serialize nodes in preorder, recording a null marker for every missing child so shape is preserved. To deserialize, track each unfinished node and whether its next child is left or right. Both operations use explicit stacks, so a long chain does not overflow the JavaScript call stack.

javascript
function serialize(root) {
  const stack = [root], values = [];
  while (stack.length) {
    const node = stack.pop();
    if (!node) values.push('null');
    else { values.push(String(node.val)); stack.push(node.right, node.left); }
  }
  return values.join(',');
}
function deserialize(data) {
  const values = data.split(',');
  if (values[0] === 'null') return null;
  const root = {val:Number(values[0]),left:null,right:null}, stack = [[root,0]];
  for (let i = 1; i < values.length; i++) {
    const frame = stack[stack.length-1], side = frame[1]++ === 0 ? 'left' : 'right';
    if (frame[1] === 2) stack.pop();
    const node = values[i] === 'null' ? null : {val:Number(values[i]),left:null,right:null};
    frame[0][side] = node;
    if (node) stack.push([node,0]);
  }
  return root;
}

Time: O(n) | Space: O(n), including the encoded string and reconstructed tree.

The runner calls serialize and deserialize in separate fresh scopes. Any string format that reconstructs the same tree is accepted. Explicit null markers distinguish left-only and right-only children, even when values repeat.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript