Count Total Nodes in Binary Tree in DSA C++ - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Once per node in the tree.
Each node is visited exactly once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The time grows linearly as the number of nodes increases.
Time Complexity: O(n)
This means the time to count nodes grows directly with the number of nodes in the tree.
[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.
Understanding this helps you explain how recursive tree traversals work and why visiting all nodes takes time proportional to the tree size.
"What if the tree was a balanced binary search tree? Would the time complexity to count nodes change?"