0
0
DSA Javascriptprogramming

Serialize and Deserialize Binary Tree in DSA Javascript

Choose your learning style9 modes available
Mental Model
We turn a tree into a string to save or send it, then rebuild the exact tree from that string.
Analogy: Like writing a family tree on paper and later using that paper to redraw the same family tree exactly.
    1
   / \
  2   3
     / \
    4   5

Serialize as: "1,2,null,null,3,4,null,null,5,null,null"
Dry Run Walkthrough
Input: Binary tree: 1 with left child 2 and right child 3; 3 has children 4 and 5
Goal: Convert the tree to a string and then rebuild the exact same tree from that string
Step 1: Start serialization at root node 1
Serialize string: "1"
Why: We record the root value first to start the string
Step 2: Serialize left child 2
Serialize string: "1,2"
Why: We add left subtree values next to keep order
Step 3: Serialize left and right children of 2 which are null
Serialize string: "1,2,null,null"
Why: We add nulls to mark no further children for node 2
Step 4: Serialize right child 3
Serialize string: "1,2,null,null,3"
Why: After left subtree, we serialize right subtree root
Step 5: Serialize left child 4 of node 3
Serialize string: "1,2,null,null,3,4"
Why: Continue preorder traversal to left child of 3
Step 6: Serialize null children of 4
Serialize string: "1,2,null,null,3,4,null,null"
Why: Mark leaf node 4's children as null
Step 7: Serialize right child 5 of node 3
Serialize string: "1,2,null,null,3,4,null,null,5"
Why: Move to right child of 3
Step 8: Serialize null children of 5
Serialize string: "1,2,null,null,3,4,null,null,5,null,null"
Why: Mark leaf node 5's children as null
Step 9: Start deserialization from string
Tokens: [1,2,null,null,3,4,null,null,5,null,null]
Why: We split string to rebuild tree nodes in order
Step 10: Create node 1, then recursively create left subtree from next tokens
Tree root: 1 with left subtree starting at 2
Why: Rebuild tree top-down matching serialization order
Step 11: Create node 2, then assign null children
Left child of 1 is 2 with no children
Why: Leaf node 2 reconstructed with null children
Step 12: Create node 3 as right child of 1, then build its children
Right child of 1 is 3 with children 4 and 5
Why: Rebuild right subtree fully
Step 13: Create node 4 with null children
Left child of 3 is 4 with no children
Why: Leaf node 4 reconstructed
Step 14: Create node 5 with null children
Right child of 3 is 5 with no children
Why: Leaf node 5 reconstructed
Result:
Tree rebuilt exactly as:
    1
   / \
  2   3
     / \
    4   5
Annotated Code
DSA Javascript
class TreeNode {
  constructor(val = 0, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function serialize(root) {
  if (root === null) return 'null';
  // serialize current node value
  const leftSerialized = serialize(root.left); // serialize left subtree
  const rightSerialized = serialize(root.right); // serialize right subtree
  return root.val + ',' + leftSerialized + ',' + rightSerialized;
}

function deserialize(data) {
  const nodes = data.split(',');
  function helper() {
    const val = nodes.shift(); // get next value
    if (val === 'null') return null; // null means no node
    const node = new TreeNode(parseInt(val)); // create node
    node.left = helper(); // build left subtree
    node.right = helper(); // build right subtree
    return node;
  }
  return helper();
}

// Driver code
const root = new TreeNode(1,
  new TreeNode(2),
  new TreeNode(3, new TreeNode(4), new TreeNode(5))
);
const serialized = serialize(root);
console.log('Serialized:', serialized);
const deserializedRoot = deserialize(serialized);

function printTree(node) {
  if (!node) return 'null';
  return node.val + ' -> ' + printTree(node.left) + ' -> ' + printTree(node.right);
}
console.log('Deserialized tree preorder:', printTree(deserializedRoot));
if (root === null) return 'null';
base case: mark null nodes explicitly
const leftSerialized = serialize(root.left);
serialize left subtree recursively
const rightSerialized = serialize(root.right);
serialize right subtree recursively
const val = nodes.shift();
read next token from serialized data
if (val === 'null') return null;
return null node when token is 'null'
node.left = helper();
build left subtree recursively
node.right = helper();
build right subtree recursively
OutputSuccess
Serialized: 1,2,null,null,3,4,null,null,5,null,null Deserialized tree preorder: 1 -> 2 -> null -> null -> 3 -> 4 -> null -> null -> 5 -> null -> null
Complexity Analysis
Time: O(n) because we visit each node once during serialization and once during deserialization
Space: O(n) for the recursion stack and the serialized string storing all nodes
vs Alternative: Compared to storing tree as nested objects or arrays, this method is compact and easy to transmit as a string
Edge Cases
Empty tree (root is null)
Serialize returns 'null' and deserialize returns null tree
DSA Javascript
if (root === null) return 'null';
Tree with only one node
Serialize returns node value with null children, deserialize rebuilds single node
DSA Javascript
if (val === 'null') return null;
Tree with only left or only right children
Nulls correctly mark missing children so tree shape is preserved
DSA Javascript
if (val === 'null') return null;
When to Use This Pattern
When you need to save or send a tree structure and later rebuild it exactly, use serialize/deserialize pattern to convert between tree and string.
Common Mistakes
Mistake: Not marking null children explicitly during serialization
Fix: Add 'null' markers for missing children to preserve tree shape
Mistake: Using split without careful order in deserialization causing wrong tree
Fix: Use a queue or shift tokens in order to rebuild tree correctly
Summary
Converts a binary tree to a string and back to the same tree.
Use when you want to save or transfer a tree structure exactly.
Mark null children explicitly to keep the tree shape during conversion.