Binary Tree Node Structure in DSA Javascript - Time & Space Complexity
We want to understand how the time to create and link nodes in a binary tree grows as we add more nodes.
How does the work change when the tree gets bigger?
Analyze the time complexity of the following code snippet.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
const root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
This code creates a simple binary tree node structure and links child nodes to the root.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and linking each node.
- How many times: Once per node created; no loops or recursion here.
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 node takes constant time, so the whole tree is always O(1)."
[OK] Correct: While one node is quick, building many nodes adds up, so total time grows with the number of nodes.
Understanding how node creation scales helps you reason about tree operations and their costs in real problems.
"What if we added a loop to create nodes instead of individual statements? How would the time complexity change?"