设n0, n1, n2为度为0, 1, 2的节点
对任意二叉树有 n0 = n2 + 1 .........(1)
对于完全二叉树而言,叶子节点只出现在最后2层. 即每个节点左右子数的高度最多相差1
可以很容易知道,完全二叉树中度为1的节点为0个或1个(即至多1个)
由n0+n1+n2=total, 且有(1)式得,
2*n0 = total +1-n1, n1 = 0或1
显然, 当total +1为偶数时, n1取0; 当total +1为奇数时, n1取1
最后, n0 = (total +1)/2, C中除法都是下取整
int
get_leaf_num(
int
total)
{
int n0;
int tmp = total + 1 ;
if (tmp % 2 == 0 )
{
n0 = tmp / 2 ;
}
else
{
n0 = (tmp - 1 ) / 2 ;
}
}
{
int n0;
int tmp = total + 1 ;
if (tmp % 2 == 0 )
{
n0 = tmp / 2 ;
}
else
{
n0 = (tmp - 1 ) / 2 ;
}
}