Count Complete Tree Nodes (LeetCode 222): Solution and Explanation
You get the root of a complete binary tree, where every level is full except maybe the last, and the last level is filled from the left. Return the number of nodes, faster than visiting all of them.
Intuition
Any traversal counts the nodes in O(n), and it is a fine answer for a quick check. The follow-up asks for something faster, which means we must count some nodes without touching them.
A perfect binary tree of height h has exactly 2^h - 1 nodes, so if we can recognise a perfect subtree we get its size for free. In a complete tree that test is cheap. The leftmost path always reaches the deepest level. The rightmost path reaches it only if the last level is full. So walk left pointers to get lh, walk right pointers to get rh, and the subtree is perfect exactly when they match.
When the heights differ, count the root as 1 and ask both children. The key fact is that at least one of the two children is always perfect: either the last level ends inside the right child (so the left child is full) or inside the left child (so the right child is a full tree one level shorter). That child answers after a single spine walk, and only the other one recurses again.
So the recursion follows a single path from the root down, doing an O(log n) spine walk at each of O(log n) levels.
Approach: Spine heights with recursion
- If
rootis null, return 0. - Set
l = r = rootand walkl = l.leftcountinglh, andr = r.rightcountingrh. - If
lh == rh, the subtree is perfect. Return(1 << lh) - 1. - Otherwise return
1 + countNodes(root.left) + countNodes(root.right).
Step-by-step example
root = [1,2,3,4,5,6]
- At node 1, the left spine is 1, 2, 4 so
lh = 3. The right spine is 1, 3 sorh = 2. They differ, so count 1 and recurse. - At node 2, the left spine 2, 4 and the right spine 2, 5 both have length 2. The subtree is perfect: 2^2 - 1 = 3 nodes.
- At node 3, the left spine 3, 6 has length 2 but the right spine is just 3, length 1. Count 1 and recurse.
- Node 6 is a single node,
lh = rh = 1, so it adds 2^1 - 1 = 1. The right child of 3 is null and adds 0. - Node 3 returns 1 + 1 + 0 = 2, and the root returns 1 + 3 + 2 = 6.
Code: Python, Java, C++
1class Solution:
2 def countNodes(self, root: Optional[TreeNode]) -> int:
3 if not root:
4 return 0
5 lh = rh = 0
6 l = r = root
7 while l:
8 lh += 1
9 l = l.left
10 while r:
11 rh += 1
12 r = r.right
13 if lh == rh:
14 return (1 << lh) - 1
15 return 1 + self.countNodes(root.left) + self.countNodes(root.right)1class Solution {
2 public int countNodes(TreeNode root) {
3 if (root == null) return 0;
4 int lh = 0, rh = 0;
5 TreeNode l = root, r = root;
6 while (l != null) {
7 lh++;
8 l = l.left;
9 }
10 while (r != null) {
11 rh++;
12 r = r.right;
13 }
14 if (lh == rh) return (1 << lh) - 1;
15 return 1 + countNodes(root.left) + countNodes(root.right);
16 }
17}1class Solution {
2public:
3 int countNodes(TreeNode* root) {
4 if (!root) return 0;
5 int lh = 0, rh = 0;
6 TreeNode* l = root;
7 TreeNode* r = root;
8 while (l) {
9 lh++;
10 l = l->left;
11 }
12 while (r) {
13 rh++;
14 r = r->right;
15 }
16 if (lh == rh) return (1 << lh) - 1;
17 return 1 + countNodes(root->left) + countNodes(root->right);
18 }
19};Time and space complexity
O(log² n)
At every call one child is perfect and returns after one spine walk, so the recursion goes down one path of length O(log n). Each call walks two spines of length O(log n).
O(log n)
The recursion depth is the height of the tree, which is O(log n) for a complete tree.
Other approaches
Plain traversal (time O(n), space O(log n))
Count every node with DFS or BFS. It is correct for any tree, and it is the right baseline, but it ignores the completeness guarantee and visits all n nodes.
Binary search on the last level (time O(log² n), space O(1))
Get the height h from the left spine, then binary search over the 2^h slots of the last level, checking whether a slot exists by walking down using the bits of its index. Same O(log² n) bound, a bit more code.
Common mistakes
- Computing the height of a child with a full recursive height function instead of a single spine walk. That turns each check into O(n) work.
- Using
2 ** hwith floating point or forgetting the minus one. A perfect tree with h levels has 2^h - 1 nodes, not 2^h. - Measuring heights as edges in one place and as nodes in another. Count nodes on the path in both spines so
lhandrhmean the same thing. - Assuming the trick works on any binary tree. Equal spine heights only prove perfection because the tree is complete.
Frequently asked questions
Why does equal left and right height mean the subtree is perfect?
In a complete tree the last level fills from the left. The leftmost path always reaches the last level and the rightmost path reaches it only when the last level has no gaps. Equal lengths therefore mean every level, including the last, is full.
Why is this O(log² n) and not O(n)?
When the spines differ, one of the two children is perfect and stops after one spine walk. Only the other child recurses further, so there are O(log n) calls on the deep path, each doing O(log n) work.
Is the plain O(n) traversal accepted?
Yes, it passes the tests. The faster solution matters in interviews because the follow-up explicitly asks you to use the complete-tree property.
Does the recursion ever hit a null child?
Yes, when the last level ends at a left child, its parent has no right child. That call simply returns 0.