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