Count Complete Tree Nodes

Given the root of a complete binary tree, return the number of nodes in the tree. In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. The last level $h$ can hold between $1$ and $2^h$ nodes. Design an algorithm that runs in less than $O(n)$ time.

30:00

Count Complete Tree Nodes
easy
Free written solution
Topics
Companies

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

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. The last level hh can hold between 11 and 2h2^h nodes.

Design an algorithm that runs in less than O(n)O(n) time.

Example 1:
Input: {"root":[1,2,3,4,5,6]}
Output: 6
Constraints:
  • The number of nodes in the tree is in the range [0,5⋅104][0, 5 \cdot 10^4].

  • 0≤Node.val≤5⋅1040 \leq \text{Node.val} \leq 5 \cdot 10^4

  • The tree is guaranteed to be complete.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3,4,5,6]}

countNodes(1): look at the subtree rooted at 1.

calls:

count(1)
123456
lh = -

vs

rh = -

walk both spines

count so far = 0

left spine
right spine
perfect block, 2^h-1
counted as +1
current call
Variables
VariableValue
node1
lh-
rh-
counted0
DepthFunction Call
Stack empty
0/18