sagelearnai

Count Complete Tree Nodes

Difficulty: Easy · Pattern: Trees & BST · LeetCode #222

Given the root of a complete binary tree (every level full except possibly the last, which is filled from the left), return the number of nodes. Do better than O(n).

Examples

text
[1,2,3,4,5,6]  →  6
[]             →  0
[1]            →  1

Hints

  1. Measure the leftmost depth and the rightmost depth. If they're equal, the tree is perfect.
  2. A perfect tree of height h has 2^h − 1 nodes. If it isn't perfect, recurse into both children. One of them is guaranteed to be perfect.

Approach

text
count(node):
  lh = depth following .left; rh = depth following .right
  if lh == rh: return 2^lh - 1        # perfect: no need to look inside
  return 1 + count(left) + count(right)

At every level, at least one of the two recursive calls hits a perfect subtree and returns right after its O(log n) spine walk. So there are O(log n) levels × O(log n) work each: O(log² n).

A further alternative binary-searches the last level, using the bits of the index as a path. That also runs in O(log² n).

Complexity

Time: O(log² n). Space: O(log n).

Python solution
def countNodes(root):
    if not root:
        return 0
    lh, n = 0, root
    while n:
        lh += 1
        n = n.left
    rh, n = 0, root
    while n:
        rh += 1
        n = n.right
    if lh == rh:
        return (1 << lh) - 1
    return 1 + countNodes(root.left) + countNodes(root.right)
JavaScript solution
function countNodes(root) {
  if (!root) return 0;
  let lh = 0, rh = 0, n = root;
  while (n) { lh++; n = n.left; }
  n = root;
  while (n) { rh++; n = n.right; }
  if (lh === rh) return 2 ** lh - 1;
  return 1 + countNodes(root.left) + countNodes(root.right);
}