|
创建二叉排序树的问题
#include<iostream>
using namespace std;
typedef struct Tree{
struct Tree *lchild,*rchild;
int data;
}TNode,*BiTree;
BiTree Search(BiTree T,int data,BiTree f,BiTree &p)
{// f初始值是NULL, 指向T的双亲
if(!T) p = f;
else if( T->data == data) p = T;
else if( T->data < data ) return Search(T->lchild,data,T,p);
else return Search(T->rchild,data,T,p);
}
void insert(BiTree &T,int data)
{
BiTree p,s;
if(!Search(T,data,NULL,p))
{
s = (BiTree)malloc(sizeof(TNode));
s->data = data; s->lchild = s->rchild = NULL;
if(!p) T = s;
else if(p->data > data) p->lchild = s;
else p->rchild = s;
}
}
void creatBiTree(BiTree &T)
{
int data;
do{
cin>>data;
insert(T,data);
}while(data!=0);
}
void printBiTree(BiTree &T)
{
if(T)
{
cout<<T->data<<endl;
printBiTree(T->lchild);
printBiTree(T->rchild);
}
}
int main()
{
BiTree t;
creatBiTree(t);
printBiTree(t);
system("pause"); |
|