loading

Count Complete Tree Nodes — Step-by-Step Visualization

easyLeetCode #222Binary SearchTreeBinary Tree

Count nodes in a complete binary tree.

Algorithm Pattern

Binary Search on Height

Key Idea

In a complete tree, left and right heights differ by at most 1. Use this to count without visiting all nodes.

Step-by-Step Approach

  1. Compute left height (go left until null)
  2. Compute right height (go right until null)
  3. If equal: 2^h - 1 + 1 (root) + recurse right
  4. Else: recurse left + 2^(h-1) - 1 + 1 (root)

Related Problems