首页 > 代码库 > 九度 1113 关于二叉树节点的个数问题

九度 1113 关于二叉树节点的个数问题

#include <stdio.h>
#include <math.h>


int main()
{
        int n,m,left,right;
        int count;
        int deep_n,deep_m,deep_diff;
        int i, j;


        for( scanf("%d%d",&m,&n); n!=0 && m!=0; scanf("%d%d",&m,&n) )
        {
                count = 0;
                left = right = m;


                deep_n = (int)(log(n)/log(2)+1); //节点n的深度
                deep_m = (int)(log(m)/log(2)+1); //节点m的深度


                deep_diff = deep_n - deep_m;     //两者的深度之差
				
				//其实可以将m节点看成一个独立的子树的根节点,就能理解此处所想表达的意思了
				//深度为deep的二叉树的节点个数为2^deep-1个,这样会好理解一点
                count += (int)pow(2,deep_diff) - 1;  


                for(i=1;i<=deep_diff;++i)
                {
                        left = 2*left;
                        right = 2*right+1;
                }


                if(right<=n)
                        count += right - left + 1;
                else if(left<=n)
                        count += n - left + 1;
                                
                printf("%d\n",count);
        }
    return 0;
}