v9.1.1
Menu

Count Complete Tree Nodes

easyPROTrees & GraphsGoogle DSA

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

Input
1,2,3,4,5,6
Output
6
Reasoning
  • Input: root is the top node of a complete binary tree. The sample 1,2,3,4,5,6 lists 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 holds 2 and 3; level 3 holds 4, 5 under 2 and 6 as the left child of 3. The right child slot of 3 is empty.
  • The math: a full level kk holds 2k−12^{k-1} nodes, so the two full top levels contribute 20+21=22−1=32^0 + 2^1 = 2^2 - 1 = 3. The last level could hold 22=42^2 = 4 nodes but has only 33, packed to the left.
  • Output: 3+3=3 + 3 = 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 2h−12^{h-1} and 2h−12^h - 1 for a tree of height hh (here between 44 and 77). An empty tree, with no root at all, has 00 nodes.

Constraints

  • 0 <= number of nodes <= 5 * 10^4
  • 0 <= Node.val <= 5 * 10^4

More from Google DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.