Count Complete Tree Nodes

easy

Given the root of a complete binary tree, return the number of nodes in it.

In a complete binary tree every level is fully filled except possibly the last, and the last level's nodes are as far left as possible. A perfect tree of height h has exactly 2^h - 1 nodes.

Design an algorithm that runs in better than O(n) time. The tree is given in level-order (breadth-first), using null for missing children.

Hints

Counting every node is O(n); completeness lets you do better.
For any subtree, compare its leftmost-spine and rightmost-spine heights.
Equal heights mean a perfect subtree of 2^h - 1 nodes; otherwise recurse into both children.

Common doubts

In a complete tree, if the leftmost and rightmost paths are the same length, every level in between must be completely filled — that's a perfect tree.
Only subtrees straddling the last level's fill boundary recurse (O(log n) of them), and each does an O(log n) spine measurement.
No — it relies on the completeness guarantee; on an arbitrary tree, equal spines don't imply perfectness.

Interview follow-ups

You'd fall back to the O(n) traversal, since the perfect-subtree shortcut no longer applies.
It has exactly 2^h - 1 nodes and 2^(h-1) leaves.

Fun facts

  • The 2^h - 1 shortcut turns whole perfect subtrees into a single arithmetic step.
  • This is one of the few tree problems where exploiting a structural guarantee beats the linear scan.

Asked at

AmazonGoogleBloomberg
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 2, 3, 4, 5, 6]
Output: 6
The complete tree has 6 nodes.
Example 2
Input: root = []
Output: 0
An empty tree has no nodes.
Example 3
Input: root = [1]
Output: 1
A single node.
Constraints

- The number of nodes is in the range [0, 5 * 10^4] - 0 <= Node.val <= 5 * 10^4 - The tree is guaranteed to be complete

Solve this problem →