AlgoInsight

DSA problem

Count Complete Tree Nodes

EasyTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop300GoogleAmazonMicrosoftAppleBloomberg

Given the root of a complete binary tree, return the number of nodes in the tree. A complete binary tree is one where every level except possibly the last is completely filled, and the last level has all its nodes pushed as far to the left as possible.

A naive traversal counts every node in O(n) time, which is acceptable but ignores the strong structural guarantee. The interesting variant of this problem asks for a sub-linear algorithm that exploits completeness.

The trick is that at every node we can compute, in O(log n) time, the leftmost path length and the rightmost path length. If they are equal — call them d — the subtree rooted at this node is a perfect binary tree, and its node count is exactly 2^d - 1 (or 2^d if you include the root, depending on how you define d). No further recursion is needed for that branch.

If the two depths differ, the last level is not full and we must split: the count is 1 + count(left) + count(right). Crucially, of those two recursive calls, exactly one descends into a perfect subtree and short-circuits, while only the other actually drills down. This gives the elegant recurrence T(n) = T(n/2) + O(log n), which solves to O(log² n) — a noticeable win for trees with billions of nodes.

Examples

Example 1
Input: root = [1,2,3,4,5,6]
Output: 6
Explanation: A complete binary tree with 6 nodes. The leftmost path has depth 2 and the rightmost path has depth 1, so we cannot short-circuit at the root and we recurse: 1 + count(left subtree=3) + count(right subtree=2) = 6.
Example 2
Input: root = []
Output: 0
Explanation: An empty tree has zero nodes.
Example 3
Input: root = [1]
Output: 1
Explanation: A single root node. Left and right depths are both 0, so the subtree is perfect with 2^0 = 1 node.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treebinary-searchdepth-first-search

Browse all DSA problems