InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Count Complete Tree Nodes

medium Original ↗ 00:00

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.

Visiting every node is straightforward. The task is to exploit completeness and count 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug