You are given the root of a complete binary tree. In a complete tree every level is fully filled except possibly the last, and the last level is packed as far left as possible.
Return the total number of nodes. A plain traversal is O(n); the goal here is to exploit the completeness property to do better.
Example 1
Input: root = [1,2,3,4,5,6]
Output: 6
The tree has two full levels plus two extra nodes on the last level.
Example 2
Input: root = [1]
Output: 1
A single root node counts as one.
Constraints
The number of nodes in the tree is in the range [0, 5 * 10^4].0 <= Node.val <= 5 * 10^4The tree is guaranteed to be complete.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI