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?"
Practice
countNodes do in a binary tree?Solution
Step 1: Understand the function purpose
The functioncountNodesis designed to traverse the binary tree and count every node it visits.Step 2: Differentiate from other tree functions
Unlike functions that find height, sum values, or check balance, this function specifically returns the total count of nodes.Final Answer:
Counts the total number of nodes in the binary tree -> Option DQuick Check:
Counting nodes = total nodes [OK]
- Confusing node count with tree height
- Thinking it sums node values
- Assuming it checks tree balance
Solution
Step 1: Identify base case for recursion
When the current node is null (no node), the count should be zero because there is no node to count.Step 2: Check each option
if (root == nullptr) return 0; returns 0 for null nodes, which is correct. Other options return incorrect values for base case.Final Answer:
if (root == nullptr) return 0; -> Option AQuick Check:
Null node count = 0 [OK]
- Returning 1 for null node
- Returning node data in base case
- Returning negative values
struct Node {
int data;
Node* left;
Node* right;
};
int countNodes(Node* root) {
if (root == nullptr) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int main() {
Node n1 = {1, nullptr, nullptr};
Node n2 = {2, nullptr, nullptr};
Node n3 = {3, &n1, &n2};
std::cout << countNodes(&n3);
return 0;
}Solution
Step 1: Analyze the tree structure
Node n3 is root with left child n1 and right child n2. Both n1 and n2 have no children.Step 2: Count nodes recursively
countNodes(n3) = 1 + countNodes(n1) + countNodes(n2) = 1 + 1 + 1 = 3Final Answer:
3 -> Option CQuick Check:
3 nodes counted [OK]
- Counting only root node
- Ignoring one child subtree
- Returning zero for non-null root
int countNodes(Node* root) {
if (root == nullptr) return 0;
return countNodes(root->left) + countNodes(root->right);
}Solution
Step 1: Check base case correctness
Base case returns 0 for nullptr, which is correct.Step 2: Check counting logic
The function sums counts of left and right subtrees but does not add 1 for the current node itself, missing counting the root.Final Answer:
Missing addition of 1 for current node -> Option AQuick Check:
Count must include current node [OK]
- Returning 1 for null node
- Not adding 1 for current node
- Confusing base case return value
Solution
Step 1: Recall property of full binary trees
In a full binary tree (nodes have 0 or 2 children), total nodes = 2 * leaf nodes - 1.Step 2: Calculate total nodes
Given leaf nodes = 7, total nodes = 2 * 7 - 1 = 13.Step 3: Verify formula and options
Formula: total nodes = 2 * leaf nodes - 1 = 2*7 -1 = 13, which matches 13.Final Answer:
13 -> Option BQuick Check:
Full binary tree nodes = 2*leaves - 1 [OK]
- Using wrong formula for total nodes
- Confusing leaf nodes with total nodes
- Selecting option without calculation
Ready to prove it?
Pass the test and this pattern moves unknown
