CodingNodes / Trees / Count Complete Tree Nodes System design Space play · ←→ step · R restart

Problem

A complete binary tree has every level full except possibly the last, and the last level is filled from the left. Given its root, return how many nodes it has.

Do better than visiting every node: use the fact that the tree is complete. The tree is given in level order, with null for a missing child.

Constraints

  • 0 ≤ number of nodes ≤ 50000
  • The tree is complete
  • Examples here have at most 10 nodes

Examples: pick one to animate

Solutions

TimeO(log² n) SpaceO(log n)

Time: Each call walks two edges of length at most log n, and only one of the two children needs real work each level, so about log n calls cost log n each.

Space: The recursion goes down one path, at most log n calls deep.

Walk down the far-left edge and the far-right edge and count nodes. If the lengths match, a complete tree must be perfect, so it holds 2^depth - 1 nodes and we are done. If not, count the node itself plus the two subtrees the same way. One of the two subtrees is always perfect, so the recursion stays on a single path.