源代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct tnode
{
int id;
int score;
struct tnode *lchild,*rchild;
}stu;
void ins_student(stu **p,long id,int score)
{
stu *s;
if(*p==NULL)
{
s=(stu *)malloc(sizeof(stu)); //插入学生信息
s->id=id;
s->score=score;
s->lchild=NULL;
s->rchild=NULL;
*p=s;
}
else if(score<(*p)->score)
ins_student(&((*p)->lchild),id,score);
else
ins_student(&((*p)->rchild),id,score);
}
//创建二叉排序树
stu *create_student()
{
int id,score;
stu *root;
root=NULL;
printf("请输入学号和成绩(用,隔开,0结束!)");
printf("
------------------------------
");
printf("学号,成绩:");
scanf("%ld,%d",&id,&score);
while(score!=0)
{
ins_student(&root,id,score);
printf("学号,成绩:");
scanf("%ld,%d",&id,&score);
}
printf("
------------------------------
");
return root;
}
void in_order(stu *bt) //二叉树的中序递归遍历
{
if(bt!=NULL)
{
in_order(bt->lchild);
printf("%ld,%d
",bt->id,bt->score);
in_order(bt->rchild);
}
}
void main()
{
stu *root;
root=create_student();
printf("排序后的结果:
");
printf("学号,成绩:
");
in_order(root);
}
运行结果: