Create a Binary Tree Manually in DSA Javascript - Time & Space Complexity
When we create a binary tree manually, we add nodes one by one. Understanding how long this takes helps us plan for bigger trees.
We want to know how the time to build the tree grows as we add more nodes.
Analyze the time complexity of the following code snippet.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Manually creating nodes and linking them
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
This code creates a binary tree by making nodes and connecting them manually.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating each node and linking it.
- How many times: Once per node added to the tree.
Each new node requires a fixed amount of work to create and link.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 node creations and links |
| 100 | 100 node creations and links |
| 1000 | 1000 node creations and links |
Pattern observation: The work grows directly with the number of nodes added.
Time Complexity: O(n)
This means the time to build the tree grows linearly with the number of nodes.
[X] Wrong: "Creating a tree manually is constant time because we just write code once."
[OK] Correct: Each node creation is a separate step that takes time, so total time grows with how many nodes you add.
Knowing how building a tree scales helps you understand more complex tree operations and shows you can reason about code efficiency.
"What if we used a loop to create and link nodes instead of writing each link manually? How would the time complexity change?"