Count Nodes in Binary Tree
Problem Statement:β
You are given the root of aΒ completeΒ binary tree. Your task is to find theΒ countΒ of nodes.
A complete binary tree is a binary tree whose, all levels except the last one are completely filled, the last level may or may not be completely filled and Nodes in the last level are as left as possible.
Design an algorithm that runs better than O(n).
Example:
Input:
root = [1,2,3,4,5,6]
Output:
6
Explanation:
There are a total of 6 nodes in the given tree.
-
Example:
β Solution 1: Iterative BFS (Level Order Traversal)β
class Solution {
public:
int countNodes(Node* root) {
// Level-order traversal using queue
queue<Node*> q;
q.push(root);
int countNode = 1;
while(!q.empty()){
Node *curr = q.front();
q.pop();
if(curr->left){
q.push(curr->left);
countNode++;
}
if(curr->right){
q.push(curr->right);
countNode++;
}
}
return countNode;
}
};
β Solution 2: Recursive DFSβ
class Solution {
public:
int countNodes(Node* root) {
// Base case: if node is null, return 0
if (root == NULL) return 0;
// Recursive case: 1 (current node) + left + right
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
π How It Worksβ
β Iterative (BFS)β
- Perform level order traversal using a queue.
- For each node visited, increment a counter.
- Explore both left and right children.
β Recursive (DFS)β
- Use postorder recursion.
- For each node, recursively count the nodes in its left and right subtrees.
- Return
1 + left_count + right_countfor each node.
π§© Key Formulaβ
-
Recursive:
count(root) = 1 + count(left) + count(right) -
Iterative:
BFS traversal β count each node encountered.
β±οΈ Time & Space Complexityβ
| Approach | Time | Space |
|---|---|---|
| Iterative BFS β | O(N) | O(N) β queue |
| Recursive DFS β | O(N) | O(H) β recursion stack |
N: number of nodesH: height of the tree
β οΈ Edge Casesβ
root == NULLβ should return0- Skewed tree (all left or all right) β handled correctly
- Perfect binary tree β still works for both
π‘ Other Approachesβ
| Approach | Time | Space | Comment |
|---|---|---|---|
| DFS Recursive β | O(N) | O(H) | Simple and clean |
| BFS Iterative β | O(N) | O(N) | Useful for large trees |
| Optimized for Complete Binary Tree | O(logΒ²N) | O(logN) | Compare heights of left/right |
π Related Problemsβ
- Leetcode 222: Count Complete Tree Nodes
- Leetcode 104: Maximum Depth of Binary Tree
- GFG: Count the Number of Nodes in a Binary Tree
- Leetcode 110: Balanced Binary Tree
π¬