二叉树递归算法,树中存放整型数
①创建一棵树
②构造递归算法,计算树中值大于x的结点的个数,int countx(Bitnode *t,int x)
#include <iostream>
using namespace std;
typedef struct BiTree {
int data;
BiTree *lchild,*rchild;
} Tree ;
class Test {
private :
Tree * t;
public:
Test() {
t = NULL;
}
Tree * PreCreateBiTree();
int Countx(Tree *t,int x);
};
Tree * Test::PreCreateBiTree()
{
Tree *T;
int c;
cin>>c;
if(c==0) {
T=NULL;
} else {
T=new Tree;
if(!T) {
cout<<"请求内存失败。"<<endl;
} else {
T->data=c;
}
T->lchild=PreCreateBiTree();
T->rchild=PreCreateBiTree();
}
return T;
}
int Test:: Countx(Tree *t,int x){
if(!t) return 0;
if(t->data>x){
return 1+Countx(t->lchild,x)+Countx(t->rchild,x);
}
else
{
return Countx(t->lchild,x)+Countx(t->rchild,x);
}
}
int main() {
Test test;
int num;
Tree *tree;
cout<<"请以先序顺序输入数元素,以'0'代表虚空元素"<<endl;
tree = test.PreCreateBiTree();
cout<<"请输入想要比较的数:"<<endl;
cin>>num;
cout<<test.Countx(tree,num);
return 0;
}