Serialize and Deserialize Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to save and restore a binary tree changes as the tree grows.
How does the work increase when the tree has more nodes?
Analyze the time complexity of the following code snippet.
function serialize(root) {
if (!root) return '';
return root.val + ',' + serialize(root.left) + serialize(root.right);
}
function deserialize(data) {
const nodes = data.split(',');
function build() {
if (!nodes.length) return null;
const val = nodes.shift();
if (val === '') return null;
const node = { val: Number(val), left: build(), right: build() };
return node;
}
return build();
}
This code saves a binary tree to a string and rebuilds it back from that string using preorder traversal.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive visits of each node in the tree during serialization and deserialization.
- How many times: Each node is visited exactly once in both serialize and deserialize functions.
As the number of nodes (n) grows, the work grows roughly the same amount because each node is processed once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits to nodes |
| 100 | About 100 visits to nodes |
| 1000 | About 1000 visits to nodes |
Pattern observation: The time grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to serialize or deserialize grows directly in proportion to the number of nodes in the tree.
[X] Wrong: "Serialization or deserialization takes more than linear time because of string operations or recursion overhead."
[OK] Correct: Each node is visited once, and string operations like split or concatenation happen proportional to n, so overall time stays linear.
Understanding this helps you explain how tree data can be saved and restored efficiently, a common skill in coding interviews and real projects.
"What if we changed the traversal order in serialization from preorder to inorder? How would the time complexity change?"
Practice
serialize and deserialize functions in the context of a binary tree?Solution
Step 1: Understand serialization
Serialization means converting a data structure like a binary tree into a string format that can be stored or transmitted.Step 2: Understand deserialization
Deserialization means converting the string back into the original binary tree structure.Final Answer:
Convert a binary tree to a string and back to a binary tree -> Option BQuick Check:
Serialize/deserialize = convert tree to/from string [OK]
- Confusing serialization with sorting
- Thinking it deletes nodes
- Mixing with tree height calculation
Solution
Step 1: Recall JavaScript function syntax
In JavaScript, functions are declared using the keywordfunctionfollowed by the name and parameters.Step 2: Check each option
function serialize(root) { /* code */ } uses correct syntax. Options A, B, and D use invalid or other language syntax.Final Answer:
function serialize(root) { /* code */ } -> Option DQuick Check:
JS function declaration = function name(params) [OK]
- Using Python or other language syntax
- Missing the 'function' keyword
- Using colons or wrong punctuation
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function serialize(root) {
if (!root) return '#';
return root.val + ',' + serialize(root.left) + ',' + serialize(root.right);
}
const root = new TreeNode(1, new TreeNode(2), new TreeNode(3));
console.log(serialize(root));Solution
Step 1: Understand the serialize function
The function uses preorder traversal: root, left, right. Null nodes are represented by '#'.Step 2: Trace the tree serialization
Root is 1, left child 2 (with no children), right child 3 (with no children). So serialization is "1,2,#,#,3,#,#".Final Answer:
"1,2,#,#,3,#,#" -> Option AQuick Check:
Preorder with '#' for null = "1,2,#,#,3,#,#" [OK]
- Confusing preorder with inorder or postorder
- Forgetting to add '#' for null children
- Mixing order of nodes in output
function deserialize(data) {
const values = data.split(',');
function build() {
if (values.length === 0) return null;
const val = values.shift();
if (val === '#') return null;
const node = new TreeNode(val);
node.left = build();
node.right = build();
return node;
}
return build();
}Solution
Step 1: Analyze the deserialize function
The function splits the string and uses shift() to get values in order, which is correct.Step 2: Check TreeNode value type
Values from split are strings. If TreeNode expects numbers, val should be converted using Number(val) or +val.Final Answer:
The TreeNode constructor should convert val to number -> Option AQuick Check:
Convert string to number for node values [OK]
- Ignoring type conversion of node values
- Reversing array unnecessarily
- Using pop() breaks preorder order
"1,2,#,#,3,4,#,#,5,#,#", which of the following binary trees is the correct deserialized structure?Solution
Step 1: Understand the serialized string format
The string uses preorder traversal with '#' for nulls: root, left subtree, right subtree.Step 2: Trace the tree structure
Root is 1, left child 2 with no children (#,#), right child 3 with left child 4 (no children) and right child 5 (no children).Final Answer:
Root 1 with left child 2 (no children), right child 3 with left 4 and right 5 -> Option CQuick Check:
Preorder string matches tree structure in Root 1 with left child 2 (no children), right child 3 with left 4 and right 5 [OK]
- Mixing left and right children
- Ignoring '#' as null nodes
- Misreading preorder order
Ready to prove it?
Pass the test and this pattern moves unknown
