c語言描述資料結構應用
2 樹的操作
2.1實驗資料
學生的學號、姓名
2.2程式要求
根據輸入資料建立一棵二叉樹(第一個輸入資料作為根節點),要求:左子樹節點的學號總比根節點小,右子樹節點的學號總比根節點大。
(1)鍵盤輸入你所在宿舍的同學資訊到二叉樹;
(2)按學號大小輸出所有同學資訊;
(3)給定學號,查詢該學號同學的姓名;
2.3程式清單及詳解
//樹的操作
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct Tree
{
int no;
char name[20];
struct Tree *left;
struct Tree *right;
};
typedef struct Tree TreeNode;
typedef TreeNode *Bitree;//
Bitree insertNode(Bitree root,int no,char *name)
{
Bitree newnode;//指標變數
Bitree current;
Bitree back;
newnode=(Bitree)malloc(sizeof(TreeNode));
{
printf("\n動態分配記憶體出錯.\n");
exit(1);
}
newnode->no=no;
strcpy(newnode->name,name);
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)//根結點為空
{
return newnode;
}
else
{
current=root;//當前變數指向的位置
while(current!=NULL)
{
back=current;
if(current->no > no)
{
current=current->left;//current指向curret所指的結點左邊
}
else
{
current=current->right;//右邊
}
}
if(back->no > no)//當while條件不成立,執行,確定那個新結點位置
{
back->left=newnode;
}
else
{
back->right=newnode;//右孩子
}
}
return root;
}
Bitree createTree() //建立二叉樹(非遞迴)
{
Bitree root=NULL;//初始化
char name[20];
int len;
int no;
int i;
printf("建立二叉樹,請輸入節點的總數量: ");
scanf("%d",&len);
for(i=0;i<len;i++)
{
printf("輸入第%d個節點(學號 姓名): ",i+1);
scanf("%d",&no);
scanf("%s",name);
root=insertNode(root,no,name);
}
return root;
}
void inOrder(Bitree ptr)
{
if (ptr != NULL)
{
inOrder(ptr->left);
printf("學號:%d\t姓名:%s\n", ptr->no, ptr->name);
inOrder(ptr->right);
}
}
//按照學號查詢二叉樹
Bitree btreeFind(Bitree ptr,int no)
{
while (ptr != NULL)
{
if (ptr->no == no)//比較是否是那個學號
{
return ptr;
}
else
{
if (ptr->no > no)
{
ptr = ptr->left;//
}
else
{
ptr = ptr->right;
}
}
}
return NULL;
}
int main()
{
Bitree root=NULL;
Bitree ptr;
int no;
root=createTree(); //建立二叉樹
printf("\n所有同學的資訊:\n");
inOrder(root);
printf("\n");
while(1)
{
printf("\n輸入要查詢的學號(輸入0退出): ");
scanf("%d",&no);
if(no<=0)
{
break;
}
ptr=btreeFind(root,no);
if(ptr==NULL)
{
printf("沒有學號%d的同學\n",no);
}
else
{
printf("學號%d的同學的姓名是:%s\n",no,ptr->name);
}
}
printf("\n");
return 0;
}