Count Complete Tree Nodes
Given the root of a complete binary tree (as a level-order array), return the number of nodes.
A complete binary tree has every level fully filled except possibly the last, which is filled from left to right.
Example
1,2,3,4,5,6
6
- Input:
rootis the top node of a complete binary tree. The sample1,2,3,4,5,6lists its values level by level, left to right; each node links to at most a left and a right child. - The tree: level 1 holds
1; level 2 holds2and3; level 3 holds4,5under2and6as the left child of3. The right child slot of3is empty. - The math: a full level holds nodes, so the two full top levels contribute . The last level could hold nodes but has only , packed to the left.
- Output:
6, a single integer. Node values play no part; only the shape matters. - Notice that "complete" pins the shape down: the count always lies between and for a tree of height (here between and ). An empty tree, with no root at all, has nodes.
Constraints
- 0 <= number of nodes <= 5 * 10^4
- 0 <= Node.val <= 5 * 10^4