源代碼:
#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("\n------------------------------\n");
printf("學號,成績:");
scanf("%ld,%d",&id,&score);
while(score!=0)
{
ins_student(&root,id,score);
printf("學號,成績:");
scanf("%ld,%d",&id,&score);
}
printf("\n------------------------------\n");
return root;
}
void in_order(stu *bt) //二叉樹的中序遞歸遍歷
{
if(bt!=NULL)
{
in_order(bt->lchild);
printf("%ld,%d\n",bt->id,bt->score);
in_order(bt->rchild);
}
}
void main()
{
stu *root;
root=create_student();
printf("排序后的結果:\n");
printf("學號,成績:\n");
in_order(root);
}
運行結果:

