150. Count Complete Tree Nodes

Medium · Binary Tree

Given the root of a complete binary tree, return the total number of nodes.

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.

You may assume the tree is represented as an array in level-order traversal, where null represents a missing node. Solve this efficiently—a naive traversal of all nodes is acceptable but an O(log² n) solution using the properties of complete trees is optimal.

Examples

Example 1
Input: [1, 2, 3, 4, 5, 6]
Output: 6
Explanation: The tree has 6 nodes total. Level-order: root=1, children=[2,3], grandchildren=[4,5,6].
Example 2
Input: [1, 2, 3, 4, 5, 6, 7]
Output: 7
Explanation: A complete binary tree with 7 nodes (all levels fully filled).

Constraints