给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/ \
2 3
/ \ /
4 5 6
输出: 6
备注:利用完全二叉树的性质来求解,当左子树的高度大于右子树的高度时,则右子树是满二叉树,即可计算出此时右子树的节点总数,然后再递归求出左子树的节点数,反之如果左子树的高度等于右子树的高度则左子树是满二叉树,先计算左子树的节点总数,再递归求右子树的节点总数,其中,计算满二叉树的节点总数可以按照公式:2^n - 1,这里我用的是左移运算符。
/**
* 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) {
if(root == nullptr)
return 0;
//计算左子树和右子树的深度
int nLeftDepth = calcDepth(root->left);
int nRightDepth = calcDepth(root->right);
//如果左子树的高度和右子树的高度相等,则左子树是满二叉树
if(nLeftDepth == nRightDepth)
return (1<<nLeftDepth) + countNodes(root->right);
//否则右子树是满二叉树
return (1<<nRightDepth) + countNodes(root->left);
}
int calcDepth(TreeNode * root)
{
int nRes = 0;
while(root)
{
nRes++;
root = root->left;
}
return nRes;
}
};