0
0
DSA Typescriptprogramming~5 mins

Create a Binary Tree Manually in DSA Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Create a Binary Tree Manually
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new node requires one step to create and link it.

Input Size (n)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: The time grows directly with the number of nodes added.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the tree grows linearly with the number of nodes you add.

Common Mistake

[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.

Interview Connect

Understanding how manual tree creation scales helps you explain basic data structure building blocks clearly and confidently in interviews.

Self-Check

"What if we added a loop to create nodes instead of manual assignments? How would the time complexity change?"