Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, 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.
Let n be the total number of the tree. It is likely that you will get a child tree as a perfect binary tree and a non-perfect binary tree (T(n/2)) at each level.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
const auto height = [&](TreeNode *cur) {
int h = 0;
while (cur != NULL) {
cur = cur->left;
++h;
}
return h;
};
auto cur = root;
int res = 0;
while (cur != NULL) {
int l = height(cur->left);
int r = height(cur->right);
if (l == r) {
// left is a full tree: count = 2 ^ h - 1 + 1
res += 1 << l;
cur = cur->right;
} else {
// right is a full tree: 2 ^ r - 1 + 1
res += 1 << r;
cur = cur->left;
}
}
return res;
}
};