222. Count Complete Tree Nodes
1. Description
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, 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.
2. Example
Example 1

Input: root = [1,2,3,4,5,6]
Output: 6
Example 2
Input: root = []
Output: 0
Example 3
Input: root = [1]
Output: 1
3. 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.
4. Solutions
Binary Search
n is the number of nodes in root
Time complexity: O($log^2n$)
Space complexity: O(1)
class Solution {
public:
int countNodes(TreeNode *root) {
if (root == nullptr) {
return 0;
}
int level_count = 0;
for (TreeNode *iter = root; iter != nullptr; iter = iter->left) {
++level_count;
}
if (level_count == 1) {
return 1;
}
int last_level_capacity = 1 << (level_count - 1);
int left = 0, right = last_level_capacity;
while (left < right) {
int middle = left + (right - left) / 2;
if (exists(root, level_count, middle)) {
left = middle + 1;
} else {
right = middle;
}
}
return last_level_capacity - 1 + left;
}
private:
bool exists(TreeNode *root, int level_count, int index) {
TreeNode *iter = root;
int bit = 1 << (level_count - 2);
while (bit > 0 && iter != nullptr) {
if ((index & bit) == 0) {
iter = iter->left;
} else {
iter = iter->right;
}
bit >>= 1;
}
return iter != nullptr;
}
};