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.
/**
* 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:
//计算完全二叉树的节点数,下面是暴力破解的方式,遍历一遍整棵树
/*void countNodes(TreeNode* root,int &n)
{
if(root != NULL) ++n;
else return;
countNodes(root->left,n);
countNodes(root->right,n);
return;
}
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
int n = 0;
countNodes(root,n);
return n;
}*/
int getHeight1(TreeNode *root)
{
if(root == NULL) return 0;
int n = 1;
while(root->left != NULL){ n++; root = root->left;}
return n;
}
int getHeight2(TreeNode *root)
{
if(root == NULL) return 0;
int n = 1;
while(root->right != NULL){ n++; root = root->right;}
return n;
}
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
int lheight = getHeight1(root->left);
int rheight = getHeight2(root->right);
if(lheight == rheight)
return pow(2,1+lheight)-1;
else
return countNodes(root->left)+countNodes(root->right)+1;
}
};