LeetCode 222: Count Complete Tree Nodes — Python Solution

Solve LeetCode 222: Count Complete Tree Nodes in Python with a perfect-subtree detection approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicBinary Tree General
Reusable patternperfect-subtree detection
ComplexityO(log^2 n) time and O(log n) recursion space

What the problem is testing

Compare leftmost and rightmost heights. Equal heights identify a perfect subtree whose size is computed directly; otherwise recurse.

Algorithm

  1. Compare leftmost and rightmost heights. Equal heights identify a perfect subtree whose size is computed directly; otherwise recurse.
  2. Maintain this invariant: Equal extreme heights in a complete subtree imply every level is full.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

LeetCode provides the list, tree, or graph node definition used by the method.

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def countNodes(self, root):
        def left_height(node):
            height = 0
            while node: height += 1; node = node.left
            return height
        def right_height(node):
            height = 0
            while node: height += 1; node = node.right
            return height
        if not root:
            return 0
        left, right = left_height(root), right_height(root)
        if left == right:
            return (1 << left) - 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

Why this is correct

The proof follows the maintained state: Equal extreme heights in a complete subtree imply every level is full. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(log^2 n) time and O(log n) recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

An empty subtree has size zero; height counts must use the same convention.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 173. Binary Search Tree Iterator · Next: 236. Lowest Common Ancestor of a Binary Tree