Count Complete Tree Nodes

EasyTrees · DFS · Binary Search on Height🧩 Tree DFSLeetCode #222 ↗Updated

Problem

Given the 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).
Input[1,2,3,4,5,6]Output6
Input[]Output0
Input[1]Output1

0 ≤ nodes ≤ 5·104  ·  0 ≤ Node.val ≤ 5·104  ·  the tree is complete  ·  Follow-up: beat O(n).

Try it yourself

Java
class Solution {
    public int countNodes(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
If the leftmost and rightmost spines have the same length 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.
PatternTree DFS

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

Time 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.

Java
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.

At a glance

LevelApproachTimeSpace
Brute ForcePlain DFS CountO(n)O(log n)
OptimalPerfect-Subtree ShortcutO(log² n)O(log n)
Common pitfalls
  • Writing 2 ^ h in Java — that's XOR; use 1 << h.
  • Comparing height(left) with height(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.
Interview tips
  • 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.
Pattern
Structural shortcut on complete/perfect trees → when the shape is guaranteed, compute sizes from heights instead of visiting nodes.
My notes saved in this browser