Count Complete Tree Nodes

EasyTreesbinary search

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a **complete** binary tree, return the number of nodes it contains. In a complete binary tree every level except possibly the last is completely filled, and the nodes of the last level are packed as far left as possible. An empty tree has 0 nodes. Counting every node is O(n). Aim for an algorithm that runs in less than linear time by exploiting the complete shape.

Examples

Input: root = [1,2,3,4,5,6]
Output: 6
Two full levels plus three nodes on the last level.
Input: root = []
Output: 0
The tree is empty.
Input: root = [1]
Output: 1
Only the root.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search problems