Skip to content
Decoder

Count Complete Tree Nodes

Medium

Problem

Given the root of a complete binary tree, return how many nodes it has. In a complete tree every level is full except possibly the last, and the last level's nodes are packed as far left as possible. Aim for better than visiting every node.

Trees in the examples are written in level order (top to bottom, left to right), the same way the tests build them.

Example 1

Input
[4, 8, 1, 6, 3]
Output
5

Example 2

Input
[10, 20, 30, 40, 50, 60, 70]
Output
7

Example 3

Input
[9, 2]
Output
2

Constraints

  • 0 <= number of nodes <= 5 * 10^4
  • 0 <= Node.val <= 5 * 10^4
  • The tree is complete.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.