利用二叉樹遍歷實現學生成績排序模塊設計(二叉排序樹)


源代碼:

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

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM