24. Serialize and Deserialize Binary Tree
hardAsked at Byju'sConvert a binary tree to a string and reconstruct the identical tree from that string.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Design an algorithm to serialize and deserialize a binary tree. Serialization is the process of converting a tree to a string so it can be stored or transmitted, and reconstructed identically later. You may pick any format as long as encode/decode are inverses.
Constraints
0 <= nodes <= 10^4-1000 <= Node.val <= 1000
Examples
Example 1
root = [1,2,3,null,null,4,5]tree reconstructed identicallyExample 2
root = []empty treeApproaches
1. Level-order with index map
BFS serialize using level order then deserialize by walking the queue and assigning children by index.
- Time
- O(n)
- Space
- O(n)
function serialize(root){if(!root)return '';const q=[root],r=[];while(q.length){const n=q.shift();if(n){r.push(n.val);q.push(n.left,n.right);}else r.push('N');}return r.join(',');}
function deserialize(s){if(!s)return null;const v=s.split(',');const root=new TreeNode(+v[0]);const q=[root];let i=1;while(q.length){const n=q.shift();if(v[i]!=='N'){n.left=new TreeNode(+v[i]);q.push(n.left);}i++;if(v[i]!=='N'){n.right=new TreeNode(+v[i]);q.push(n.right);}i++;}return root;}Tradeoff:
2. Pre-order with null sentinels
DFS pre-order serialize each node and emit a sentinel ('N') for nulls. Deserialize consumes the queue recursively, recreating the same shape.
- Time
- O(n)
- Space
- O(n)
function serialize(root) {
const out = [];
const dfs = (n) => {
if (!n) { out.push('N'); return; }
out.push(n.val);
dfs(n.left); dfs(n.right);
};
dfs(root);
return out.join(',');
}
function deserialize(data) {
const tokens = data.split(',');
let i = 0;
const build = () => {
if (tokens[i] === 'N') { i++; return null; }
const node = new TreeNode(+tokens[i++]);
node.left = build();
node.right = build();
return node;
};
return build();
}Tradeoff:
Byju's-specific tips
Byju's K-12 lesson trees are persisted to JSON daily, so frame serialize/deserialize as 'curriculum snapshot transport' to land bonus signal.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Serialize and Deserialize Binary Tree and other Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →