一、 实验目的
1.熟悉二叉树的链式存储结构
2.掌握二叉树的建立、深度优先递归遍历等算法
3.能够利用遍历算法实现一些应用
二、实验内容
1.已知二叉树采用二叉链表存储结构,编写一个算法交换二叉树所有左、右子树的位置,即结点的左子树变为结点的右子树,右子树变为左子树。(文件夹:交换左右子树)
//交换左右子树的程序代码
#include<stdio.h>
#include<malloc.h>
//二叉链表的结构类型定义
const int maxsize=1024;
typedef char datatype;
typedef struct node
{
datatype data;
struct node *lchild,*rchild;
}bitree;
bitree*creattree();
void preorder(bitree*);
bitree*swap(bitree*);
void main()
{
bitree*pb;
pb=creattree();
preorder(pb);
printf("\n");
swap(pb);
preorder(pb);
printf("\n");
}
//二叉树的建立
bitree*creattree()
{
char ch;
bitree*Q[maxsize];
int front,rear;
bitree*root,*s;
root=NULL;
front=1;rear=0;
printf("按层次输入二叉树,虚结点输入'@',以'#'结束输入:\n");
while((ch=getchar())!='#')
{
s=NULL;
if(ch!='@')
{
s=(bitree*)malloc(sizeof(bitree));
s->data=ch;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)root=s;
else
{
if(s&&Q[front])
if(rear%2==0)Q[front]->lchild=s;
else Q[front]->rchild=s;
if(rear%2==1)front++;
}
}
return root;
}
//先序遍历按层次输出二叉树
void preorder(bitree*p)
{
if(p!=NULL)
{
printf("%c",p->data);
if(p->lchild!=NULL||p->rchild!=NULL)
{
printf("(");
preorder(p->lchild);
if(p->rchild!=NULL)printf(",");
preorder(p->rchild);
printf(")");
}
}
}
//交换左右子树
bitree * swap(bitree* T )
{
bitree * p;
if( T!= NULL)
{
p=T->lchild;
T->lchild=T->rchild;
T->rchild=p;
swap( T -> lchild);
swap( T->rchild);
}
return T;
}
2.采用二叉链表结构存储一棵二叉树,编写一个算法统计该二叉树中结点总数及叶子结点总数。(文件夹:统计二叉树结点)
//统计结点总数及叶子结点总数的程序代码
#include<stdio.h>
#include<malloc.h>
//二叉链表的结构类型定义
const int maxsize=1024;
typedef char datatype;
typedef struct node
{
datatype data;
struct node *lchild,*rchild;
}bitree;
bitree*creattree();
void preorder(bitree*);
int countnode(bitree*);
int countleaf(bitree*);
void main()
{
bitree*root;
int leafnum,nodenum;
root=creattree();
printf("删除子树之前的二叉树:");
preorder(root);
printf("\n");
nodenum=countnode(root);
printf("结点总数是:%d\n",nodenum);
leafnum=countleaf(root);
printf("叶子结点总数是:%d\n",leafnum);
}
//建立二叉树
bitree*creattree()
{
datatype ch;
bitree*Q[maxsize];
int front,rear;
bitree*root,*s;
root=NULL;
front=1;rear=0;
printf("按层次输入结点值,虚结点输入'@',以换行符结束:");
while((ch=getchar())!='\n')
{
s=NULL;
if(ch!='@')
{
s=(bitree*)malloc(sizeof(bitree));
s->data=ch;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)root=s;
else
{
if(s&&Q[front])
if(rear%2==0)Q[front]->lchild=s;
else Q[front]->rchild=s;
if(rear%2==1)front++;
}
}
return root;
}
//先序遍历输出二叉树
void preorder(bitree*p)
{
if(p!=NULL)
{
printf("%c",p->data);
if(p->lchild!=NULL||p->rchild!=NULL)
{
printf("(");
preorder(p->lchild);
if(p->rchild!=NULL) printf(",");
preorder(p->rchild);
printf(")");
}
}
}
//统计结点个数
int countnode(bitree* p)
{
static int count=0;
if (p ==NULL) return 0;
else
return ( 1+countnode(p->lchild) + countnode (p->rchild));
}
//统计叶子结点个数
int countleaf(bitree* p)
{
static int count1=0;
if(p!=NULL)
{
count1 = countleaf(p->lchild);
if( (p->lchild==NULL) && (p->rchild == NULL)) count1=count1+1;
count1=countleaf(p->rchild);
}
return count1;
}