hardTreeBinary SearchTrees

Count Complete Tree Nodes

hardTime: O(log^2 n)Space: O(log n)

Recognize the pattern

count nodes in a complete binary treebetter than O(n)exploit complete tree property

Brute force idea

A straightforward first read of Count Complete Tree Nodes is this: Visit every node and count. Ignores the complete tree structure entirely. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in Count Complete Tree Nodes is this: Compare left and right subtree heights. If equal, the left subtree is perfect — its count is 2^h - 1. Recurse on right. If unequal, the right subtree is perfect at one level shorter. Recurse on left. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Count Complete Tree Nodes is one steady idea: In a complete binary tree, at least one subtree is always a perfect binary tree. A perfect tree of height h has exactly 2^h - 1 nodes — no need to traverse it. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

A common way to get lost in Count Complete Tree Nodes is this: Computing height by traversing the whole subtree — in a complete tree, height = number of left-most children. per height check. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Trees Pattern