InterviewPrepKit

Home / Coding / Trees

Count Complete Tree Nodes

medium Original β†—
Solving tips
  • The trick is beating O(n): exploit that a perfect tree of height h has exactly 2^h - 1 nodes, measurable by one spine walk.
  • At each node compare left-spine and right-spine depths; if equal the subtree is perfect (use the formula), otherwise recurse β€” one side always resolves instantly, giving O(log^2 n).
  • Alternative: binary-search the count of last-level leaves (they are left-packed, so existence is monotone), testing leaf index via its bit-path in O(log n).
  • Pitfall: keep the node-vs-edge height convention consistent, and don't claim O(log n) β€” re-measuring spines at each level makes it genuinely O(log^2 n).

Problem

You are given the root of a complete binary tree: every level is fully filled except possibly the last, and the last level’s nodes are packed as far left as possible. Return the total number of nodes.

Counting by visiting every node is easy β€” the real task is to exploit completeness and do it in less than O(n) time.

Examples

Example 1

Input:  root = [1, 2, 3, 4, 5, 6]

            1
          /   \
         2     3
        / \   /
       4   5 6

Output: 6

Two full levels (3 nodes) plus 3 left-packed nodes on the last level.

Example 2

Input:  root = []
Output: 0

Empty tree, zero nodes.

Example 3

Input:  root = [1, 2, 3, 4, 5, 6, 7]
Output: 7

A perfect tree of height 3 has 2^3 - 1 = 7 nodes β€” no traversal needed once you know it’s perfect.

Constraints

  • Number of nodes is in [0, 5 * 10^4].
  • 0 <= Node.val <= 5 * 10^4
  • The tree is guaranteed complete β€” this is the property your algorithm must exploit.
  • Target complexity: better than O(n); the classic answers run in O(log^2 n).

Think about it first

Hint 1 If the tree were *perfect* (every level full), how many nodes would it have as a function of its height β€” and how cheaply can you measure the height?
Hint 2 In a complete tree, walk left-only and right-only from the root. If those two depths are equal, the tree is perfect and you're done with a formula. If not, what do you know about the left and right subtrees?
Hint 3 Both subtrees of any node in a complete tree are themselves complete, and at least one of them is perfect. Recurse: at each node, compare left-spine and right-spine heights; one side resolves by formula, the other by recursion β€” only O(log n) recursive steps, each doing an O(log n) height walk. Alternatively, binary-search for the last existing leaf using bit-path navigation.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.