0
0
DSA C++programming~5 mins

Count Total Nodes in Binary Tree in DSA C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Count Total Nodes in Binary Tree
O(n)
Understanding Time Complexity

We want to understand how the time needed to count all nodes in a binary tree changes as the tree grows.

How does the work increase when the tree has more nodes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int countNodes(TreeNode* root) {
    if (root == nullptr) return 0;
    return 1 + countNodes(root->left) + countNodes(root->right);
}
    

This code counts all nodes by visiting each node once, adding 1 for the current node plus counts from left and right subtrees.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Recursive calls visiting each node once.
  • How many times: Once per node in the tree.
How Execution Grows With Input

Each node is visited exactly once, so the work grows directly with the number of nodes.

Input Size (n)Approx. Operations
10About 10 visits
100About 100 visits
1000About 1000 visits

Pattern observation: The time grows linearly as the number of nodes increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to count nodes grows directly with the number of nodes in the tree.

Common Mistake

[X] Wrong: "Counting nodes is faster because it just adds 1 without looping much."

[OK] Correct: Even though adding 1 is simple, the function must visit every node to count it, so the total work depends on the tree size.

Interview Connect

Understanding this helps you explain how recursive tree traversals work and why visiting all nodes takes time proportional to the tree size.

Self-Check

"What if the tree was a balanced binary search tree? Would the time complexity to count nodes change?"