利用二叉树遍历实现学生成绩排序模块设计(二叉排序树)

源代码:

#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);
}

运行结果:

 

posted @ 2019-10-31 11:01  bobo哥  阅读(1699)  评论(0编辑  收藏  举报