> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Count Complete Tree Nodes Python Solution

> Tested Python solution for LeetCode 222 with 32 pytest cases. Generate a practice environment with lcpy.

LeetCode 222, [Medium](/catalog/medium). Topics: [Binary Search](/catalog/topics/binary-search), [Bit Manipulation](/catalog/topics/bit-manipulation), [Tree](/catalog/topics/tree), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/count-complete-tree-nodes/description/).

Generate this problem as a practice environment: tested reference solution, 32 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 222   # by problem number
lcpy gen -s count_complete_tree_nodes   # by problem name
```

## Problem

Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.

According to Wikipedia's definition of a complete binary tree, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2^h` nodes inclusive at the last level `h`.

Design an algorithm that runs in less than `O(n)` time complexity.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/01/14/complete.jpg)

```
Input: root = [1,2,3,4,5,6]
Output: 6
```

```
Input: root = []
Output: 0
```

```
Input: root = [1]
Output: 1
```

### Constraints

* The number of nodes in the tree is in the range `[0, 5 * 10^4]`.
* `0 <= Node.val <= 5 * 10^4`
* The tree is guaranteed to be **complete**.

**Follow up:** Design an algorithm that runs in less than `O(n)` time complexity.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/count_complete_tree_nodes/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/count_complete_tree_nodes/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(log^2 n)
    # Space: O(1)
    def count_nodes(self, root: TreeNode[int] | None) -> int:
        if root is None:
            return 0

        left_depth = 0
        node = root
        while node.left is not None:
            left_depth += 1
            node = node.left

        def exists(index: int) -> bool:
            current = root
            for shift in range(left_depth - 1, -1, -1):
                if current is None:
                    return False
                current = current.right if (index >> shift) & 1 else current.left
            return current is not None

        low, high = 1, 1 << left_depth
        while low < high:
            mid = (low + high + 1) // 2
            if exists(mid - 1):
                low = mid
            else:
                high = mid - 1
        return (1 << left_depth) - 1 + low
```

## Complexity

| Time | Space |
| - | - |
| O(log^2 n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.