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 2h 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 + Bit
n = nodes of root
Time complexity: O($log^2n$)
Space complexity: O(1)
class Solution {
public:
int countNodes(TreeNode *root) {
if (!root) {
return 0;
}
int depth = 0; // include root
for (auto iter = root; iter; iter = iter->left) {
++depth;
}
size_t min_count = (1 << (depth - 1));
size_t max_count = (1 << depth) - 1;
// for the case we only have a root node, it will not go through the following loop
// I don't want to write another if statement
int result = 1;
for (int left = min_count, right = max_count, mid = (min_count + max_count) / 2;
left <= right;) {
bool has_node = false;
// if depth is 3, we only need to move 2 times
// 1 << 0 == 1, so we deduct 1 twice
int digit = depth - 1 - 1;
for (auto iter = root; digit >= 0; --digit) {
iter = (mid & (1 << digit)) == 0 ? iter->left : iter->right;
has_node = (iter != nullptr);
}
has_node ? result = mid, left = mid + 1 : right = mid - 1;
mid = (left + right) / 2;
}
return result;
}
};