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.
Code:
/**
* 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 countDepth(TreeNode* root, int dir) {
int ret = 0;
while (root) {
++ret;
if (dir == 0)
root = root->left;
else
root = root->right;
}
return ret;
}
int countNodes(TreeNode* root) {
if (root == NULL) {
return 0;
} else if (root->left == NULL) {
return 1;
} else if (root->right == NULL) {
return 2;
} else {
int d0, d1;
d0 = countDepth(root, 0);
d1 = countDepth(root, 1);
if (d0 == d1) {
return pow(2, d0) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
}
};