Count Total Nodes in Binary Tree in DSA Java - Time & Space Complexity
We want to know how long it takes to count all nodes in a binary tree as the tree grows.
How does the time needed change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
public int countNodes(TreeNode root) {
if (root == null) 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 call 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 in direct proportion to the number of nodes in the tree.
[X] Wrong: "Counting nodes is faster because we only add 1 each time, so it's constant time."
[OK] Correct: Even though adding 1 is simple, the function must visit every node to count it, so time grows with the number of nodes.
Understanding how recursive tree traversal scales helps you explain and write efficient tree algorithms confidently.
"What if we changed the tree to be a balanced binary search tree? How would the time complexity change?"
Practice
Solution
Step 1: Understand the node counting function
The function visits every node in the tree, including root, left, and right children.Step 2: Summarize the counting process
It adds 1 for the current node plus counts from left and right subtrees recursively.Final Answer:
It counts all nodes including root, left, and right children. -> Option AQuick Check:
Total nodes = all nodes in tree [OK]
- Counting only leaf nodes
- Ignoring one subtree
- Counting nodes twice
Solution
Step 1: Identify method return type and parameters
The method should return an integer count and accept the root node as parameter.Step 2: Match correct Java syntax
public int countNodes(TreeNode root) correctly declares public int countNodes(TreeNode root) which returns count.Final Answer:
public int countNodes(TreeNode root) -> Option AQuick Check:
Method returns int and takes root node [OK]
- Using void return type
- Missing root parameter
- Incorrect access modifier
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class Main {
public static int countNodes(TreeNode root) {
if (root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
System.out.println(countNodes(root));
}
}Solution
Step 1: Count nodes in the tree structure
The tree has nodes: 1 (root), 2 (left), 3 (right), and 4 (left-left child). Total 4 nodes.Step 2: Apply recursive countNodes function
Function returns 1 + count of left subtree + count of right subtree = 4.Final Answer:
4 -> Option BQuick Check:
Nodes counted = 4 [OK]
- Forgetting to count root node
- Miscounting null children
- Confusing node values with count
public int countNodes(TreeNode root) {
if (root == null) {
return 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}Solution
Step 1: Check base case for null node
Function returns 1 when root is null, which is incorrect; it should return 0.Step 2: Verify counting logic
The counting logic correctly adds 1 for the current node and recurses to both subtrees.Final Answer:
Returns 1 when root is null instead of 0 -> Option CQuick Check:
Base case must return 0 for null [OK]
- Returning 1 for null node
- Not adding 1 for current node
- Incorrect recursion calls
Solution
Step 1: Use property of full binary tree
In a full binary tree, number of leaf nodes = number of internal nodes + 1.Step 2: Calculate leaf nodes from total nodes
Total nodes = leaf nodes + internal nodes = 15. So leaf nodes = internal nodes + 1. Let internal nodes = x, then x + (x + 1) = 15 -> 2x + 1 = 15 -> 2x = 14 -> x = 7. Leaf nodes = 7 + 1 = 8.Final Answer:
8 -> Option DQuick Check:
Leaf nodes = internal nodes + 1 = 8 [OK]
- Confusing total nodes with leaf nodes
- Forgetting full binary tree property
- Incorrect algebra for leaf count
Ready to prove it?
Pass the test and this pattern moves unknown
