算是一种递归完成的中序遍历,检查当前子树等价于检查左子树、根节点和右子树。
//例题8.4 二叉树
#include <iostream>
#include <algorithm>
using namespace std;
int sum;
void count_num(int m,int n){
if(m>n)return;
sum++;
count_num(2*m,n);
count_num(2*m+1,n);
return ;
}
int main(){
int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
if(m==0)break;
sum=0;
count_num(m,n);
cout<<sum<<endl;
}
return 0;
}
也可以不用全局变量:
//例题8.4 二叉树(思路一样但是更优雅的解法)
int count_num(int m,int n){
if(m>n)return 0;
return 1+count_num(2*m,n)+count_num(2*m+1,n);
}
int main(){
int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
if(m==0)break;
printf("%d\n",count_num(m,n));
}
return 0;
}