SDE & MLE Prep

222. Count Complete Tree Nodes

Problem

Count the nodes of a complete binary tree (every level full except possibly the last, whose nodes are packed to the left) in less than O(n) time.

Example: [1,2,3,4,5,6] → 6

Constraints: up to 5·10⁴ nodes.

Compare the leftmost and rightmost depths. Equal ⇒ the subtree is perfect: 2^h − 1 nodes. Otherwise recurse into both children — only one side is non-perfect at each level.

Complexity: O(log² n).

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        l = r = root
        hl = hr = 0
        while l:
            l, hl = l.left, hl + 1
        while r:
            r, hr = r.right, hr + 1
        if hl == hr:
            return (1 << hl) - 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)