Count Complete Tree Nodes
Problem
root of a complete binary tree — every
level is full except possibly the last, whose nodes are packed to the left —
return how many nodes it has. Aim for better than O(n).[1,2,3,4,5,6]Output6[]Output0[1]Output10 ≤ nodes ≤ 5·104 · 0 ≤ Node.val ≤ 5·104 · the tree is complete · Follow-up: beat O(n).
Try it yourself
class Solution {
public int countNodes(TreeNode root) {
}
}
h,
the tree is perfect and has 2h - 1 nodes — no need
to visit them. In a complete tree, at least one child subtree is always perfect, so only
one branch per level needs real work.Instinct If the answer for a node can be built from the answers of its left and right subtrees, write one recursive function and trust it on the children.
Memory hack Ask the kids, then decide - each child reports up, the parent combines, and a global variable keeps the best "bend" seen so far.
Open the Tree DFS guide →Approaches
Brute ForcePlain DFS Count
O(n)Space O(log n)Ignore completeness: a tree's size is 1 + size(left) +
size(right), with an empty tree counting 0. Every node is visited once;
the recursion depth is the height, which is O(log n) for a complete tree.
public int countNodes(TreeNode root) { if (root == null) return 0; return 1 + countNodes(root.left) + countNodes(root.right); }
Always correct, but wastes the “complete” guarantee and misses the follow-up.
OptimalPerfect-Subtree Shortcut
O(log² n)Space O(log n)Measure the left spine and right spine (O(log n) each). Equal ⇒
perfect, return 2h - 1 at once. Otherwise recurse into
both children: one of them is perfect and returns after its spine check, so only
one O(log n) path goes deeper — O(log n) levels × O(log n) work.
public int countNodes(TreeNode root) { if (root == null) return 0; int lh = 0, rh = 0; for (TreeNode n = root; n != null; n = n.left) lh++; for (TreeNode n = root; n != null; n = n.right) rh++; if (lh == rh) return (1 << lh) - 1; // perfect tree: 2^h - 1 nodes return 1 + countNodes(root.left) + countNodes(root.right); }
Exploits completeness to skip whole perfect subtrees — answers the follow-up.
At a glance
| Level | Approach | Time | Space |
|---|---|---|---|
| Brute Force | Plain DFS Count | O(n) | O(log n) |
| Optimal | Perfect-Subtree Shortcut | O(log² n) | O(log n) |
- Writing
2 ^ hin Java — that's XOR; use1 << h. - Comparing
height(left)withheight(right)via full DFS — back to O(n). - Measuring only the left spine — it can't tell a perfect tree from a partially filled one.
- Give the O(n) count first, then ask yourself what “complete” buys you.
- Argue the O(log² n) bound: at most one non-perfect child per level.
- Mention the last-level binary search as an equivalent alternative.