本题源自leetcode 222
-----------------------------------------------------------------------
思路:完全二叉树,的结点个数。1 如果左子树的高度等于右子树的高度。则为完全二叉树。节点个数等于2的树高次幂-1;
否则就递归遍历左子树节点和右子树节点,再加上根节点。
代码:
int countNodes(TreeNode* root) {
if(!root)
return 0;
TreeNode *l=root;
TreeNode* r=root;
int hl=0,hr=0;
while(l){
l=l->left;
hl++;
}
while(r){
r=r->right;
hr++;
}
if(hr == hl){
return pow(2,hl)-1;
}
return countNodes(root->left)+countNodes(root->right)+1;
}
思路: 分别计算左子树和右子树的左子树的高度。如果相等,则说明左子树是完全二叉树。否则,右子树比左子树低1,右子树为完全二叉树。
代码2:
int countNodes(TreeNode* root) {
if(!root)
return 0;
int left=getLeftHigh(root->left);
int right=getLeftHigh(root->right);
if(left == right)
return pow(2,left)+countNodes(root->right); //左子树为完全二叉树
return pow(2,right)+countNodes(root->left); //右子树为完全二叉树。且高度比左子树少1
}
int getLeftHigh(TreeNode* root){
if(!root)
return 0;
int high=0;
while(root){
root=root->left;
high++;
}
return high;
}