该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include
#include
#include
/*
1. 参照实验教材,完成第5章 《树结构的应用》实验。
2. 在二叉排序树实验中,增加算法实现,求二叉排序树的高度。
*/
typedef int KeyType; //定义二叉排序树关键字类型为整型
typedef struct node
{
KeyType score; //成绩为排序关键字
char num[8];
char name[9];
char gender[3];
struct node *lchild, *rchild;
}BSTNode;
typedef BSTNode *BSTree;
void InsertBST(BSTree *TPtr,BSTNode *stuInfo) //TPr是指向二叉树的指针
{
BSTNode *f,*p=*TPtr;
while(p) //查到叶子结点为止
{
f=p; //f为应插入位置的双亲结点
p=((stuInfo->score)<=(p->score))? p->lchild:p->rchild;
/*这里使用指针p,指向正在查找的结点
指针f,指向正在查找结点的双亲结点*/
p=(BSTNode *)malloc(sizeof(BSTNode)); //生成新结点
p->score=stuInfo->score;
strcpy(p->num,stuInfo->num);
strcpy(p->name,stuInfo->name);
strcpy(p->gender,stuInfo->gender);
p->lchild=p->rchild=NULL;
/*生成二叉树的新结点,令p指向该新结点*/
if(*TPtr==NULL)
*TPtr=p; //若树为空,令待插入的结点为新二叉树的根结点
else
if(stuInfo->score<=f->score) f->lchild=p;
else f->rchild=p;
/*将新生成的结点插入到正确的位置*/
}
}
BSTree CreateBST(void)
{
BSTree T = NULL; //排序树根节点T
BSTNode *stuInfo;
char flag = 'y';
stuInfo = (BSTNode *)malloc(sizeof(BSTNode));
printf("\n请输入学生信息\n");
while(flag=='y'||flag=='Y')
{
printf("\n学号(8) 姓名(9) 性别 成绩\n");
scanf("%s%s%s%d",
stuInfo->num,stuInfo->name,stuInfo->gender,&stuInfo->score);
InsertBST(&T,stuInfo);
printf("继续输入吗?(y/n):");
flag = getch();
}
return T;
}
void InOrder(BSTree root)
{
if(root!=NULL)
{
InOrder(root->lchild);
printf("%s,%s,%s,%d\n",root->num,root->name,root->gender,root->score);
InOrder(root->rchild);
}
}
BSTNode *SearchBST(BSTree T, KeyType stuScore)
{
if(T==NULL || stuScore==T->score) return T;
if(stuScore <= T->score)
return SearchBST(T ->lchild,stuScore);
if(stuScore > T->score)
return SearchBST(T ->rchild,stuScore);
}
void main()
{
BSTree root; //指向根结点
BSTNode *student;
KeyType stuScore;
printf("\n生成二叉排序树:\n");
root = CreateBST(); //调用函数,生成二叉排序树*
printf("\n中根遍历二叉树,输出结果\n");
printf("\n学号(8) 姓名(9) 性别 成绩\n");
printf("-------------------------------------------\n");
InOrder(root); //调用函数,中根遍历二叉排序树,并输出遍历结果
printf("\n利用二叉排序树进行查栈:\n");
printf("\n请输入要查询的学生成绩:\n");//调用函数,在二叉排序树中进行学生成绩查找
scanf("%d",&stuScore);
student=SearchBST(root,stuScore);
if(!student)
printf("没有查到成绩为%d的学生",stuScore);
else {
printf("成绩为%d的学生信息:",stuScore);
printf("%s,%s,%s,%d\n",
student->num,student->name,student->gender,student->score);
}
getch();
}