求普通二叉树的节点个数,只需要遍历一遍即可:
int NodeCount(TreeNode* root)
{
if(root==nullptr)
{
return 0;
}
return 1+NodeCount(root->left)+NodeCount(root->right);
}
求满二叉树的节点个数,可以根据满二叉树的性质:节点个数等于2^N-1,其中N为这棵满二叉树的高度。因此随便挑一个方向往下遍历即可
int NodeCount(TreeNode* root)
{
int height=0;
while(root!=nullptr)
{
root=root->left;
height++;
}
return (int)Math.pow(2,height ) - 1;
}
求完全二叉树的高度,就需要将前两种树的性质结合起来。
因为完全二叉树内一定包含满二叉树,所以此时可以通过按照2^N-1的性质以节省时间。
int NodeCount(TreeNode* root)
{
int leftheight=0;
TreeNode* L=root;
int rightheight=0;
TreeNode* R=root;
while(L!=nullptr)
{
L=L->left;
leftheight++;
}
while(R!=nullptr)
{
R=R->right;
rightheight++;
}
if(leftheight==rightheight)
{
return (int)Math.pow(2,leftheight ) - 1;
}
return 1+NodeCount(root->left)+NodeCount(root->right);
}