A binary tree is handed to you by its root, and the tree is complete. Count its nodes and return the total.
In a complete binary tree, every level is full except perhaps the last one, and the nodes on the last level sit as far left as they can. Counting every node is easy; try to do it in less than O(n) time.
Example 1
Input: root = [5, 9, 2, 7, 1, 8] Output: 6 Why: two full levels, then three nodes from the left
2 more examples and the constraints
Example 2
Input: root = [] Output: 0 Why: an empty tree has no nodes
Example 3
Input: root = [10, 20, 30, 40, 50, 60, 70] Output: 7 Why: three full levels: 1 + 2 + 4
Constraints
- The tree has between 0 and 50,000 nodes
- 0 ≤ each node value ≤ 50,000
- The tree is always complete
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count every nodeO(n)
- Skip perfect subtreesO(log² n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 nodes | Verdict |
|---|---|---|---|
| Count every node | O(n) | Correct, but O(n) | |
| Skip perfect subtrees | O(log² n) | Best; a few hundred steps |
n = number of nodes; log n is the height of the tree, about 16 here.
Edge cases to test
- An empty tree. [] has no root: return 0 before measuring anything.
- A single node. [0] has two edges of length 1, so it is perfect: 2¹ − 1 = 1.
- A root with only a left child. [3, 4]: left edge 2, right edge 1, so split: 1 + 1 + 0 = 2.
- One node on a new level. With 8 nodes, the left subtree is not perfect but the right one is, so the count still skips most of the tree.
Common mistakes
- Writing
2 ^ h - 1in Java, C++ or TypeScript, where^is XOR, not a power; use(1 << h) - 1. - Measuring only the left edge and assuming the tree is perfect.
- Counting edges instead of nodes along the walk, which is off by one in the 2^h − 1 formula.
How to talk through it
- 1Clarify. Is the tree guaranteed to be complete? Can it be empty?
- 2Give the plain count. One plus the sizes of both subtrees: O(n), but it ignores completeness.
- 3Use the shape. If the left and right edges have the same length, the subtree is perfect and has 2^h − 1 nodes.
- 4State the cost. One child is always perfect, so the recursion follows one path down: O(log n) levels times O(log n) per edge walk.
- 5Test out loud. Run an empty tree, a single node, and a tree whose last level holds one node.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?