Create a Binary Tree Manually in DSA Typescript - Time & Space Complexity
When we create a binary tree manually by adding nodes one by one, it is important to understand how the time needed grows as the tree gets bigger.
We want to know how long it takes to build the tree as we add more nodes.
Analyze the time complexity of the following code snippet.
class TreeNode {
value: number;
left: TreeNode | null = null;
right: TreeNode | null = null;
constructor(value: number) {
this.value = value;
}
}
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
This code creates a binary tree by manually assigning child nodes to the root and its children.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and linking each node manually.
- How many times: Once per node added, no loops or recursion here.
Each new node requires one step to create and link it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The time grows directly with the number of nodes added.
Time Complexity: O(n)
This means the time to create the tree grows linearly with the number of nodes you add.
[X] Wrong: "Creating a binary tree manually is always very slow because it involves complex operations."
[OK] Correct: Actually, each node is created and linked in a simple step, so the time grows only as you add more nodes, not more complex than that.
Understanding how manual tree creation scales helps you explain basic data structure building blocks clearly and confidently in interviews.
"What if we added a loop to create nodes instead of manual assignments? How would the time complexity change?"