实验四 二叉树基本操作的实现

时间:2021-07-31 19:08:03

实现链式储存创建,递归先序 中序 后序遍历,叶子结点数,数的结点总数,交换左右子树


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int cnt;
//结点声明,数据域 左子树 右子树
typedef struct BiNode
{
char data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
//创建二叉树
/*void Init(BiTree T)
{
T=NULL;
return;
}*/
BiTree Creat_BiTree()
{
BiTree T;
char ch;
scanf("%c",&ch);
if(ch=='#')
T=NULL;
else
{
T=(BiNode *)malloc(sizeof(BiNode));//为结点申请一个sizeof(BiNode)大小的空间
T->data=ch;
T->lchild=Creat_BiTree();//建立左子树
T->rchild=Creat_BiTree();//建立右子树
}
return T;
}
//先序遍历
void Pre_order(BiTree T)
{
if(T)
{
printf("%c",T->data);
Pre_order(T->lchild);
Pre_order(T->rchild);
}
}
//中序遍历
void In_order(BiTree T)
{
if(T)
{
In_order(T->lchild);
printf("%c",T->data);
In_order(T->rchild);
}
}
//后序遍历
void Post_order(BiTree T)
{
if(T)
{
Post_order(T->lchild);
Post_order(T->rchild);
printf("%c",T->data);
}
}
//二叉树叶子总结点数
int Num_BiTree(BiTree T)
{
if(T==NULL)
return 0;
if(T->lchild==NULL&&T->rchild==NULL)
{
cnt++;
}
return Num_BiTree(T->lchild)+Num_BiTree(T->rchild)+1;
}
//交换左右子树
void Change_child(BiTree T)
{
BiTree temp;
if(T==NULL)
return ;
else
{
Change_child(T->lchild);
Change_child(T->rchild);
temp=T->lchild;
T->lchild=T->rchild;
T->rchild=temp;
}
}
int main()
{
BiTree T;
printf("********二叉树的基本操作********\n\n");
printf("\n创建链式储存二叉树:\n");
T=Creat_BiTree();
/******三种遍历方式******/
printf("\n输出先序遍历二叉树:\n");
Pre_order(T);
printf("\n输出中序遍历二叉树:\n");
In_order(T);
printf("\n输出后序遍历二叉树:\n");
Post_order(T);
cnt=0;
int ans=Num_BiTree(T);
printf("\n\n输出二叉树叶子总结点和叶子结点数:\n");
printf("%d %d\n",ans,cnt);
Change_child(T);
printf("\n交换左右子树后输出遍历结果\n");
/******三种遍历方式******/
printf("\n输出先序遍历二叉树:\n");
Pre_order(T);
printf("\n输出中序遍历二叉树:\n");
In_order(T);
printf("\n输出后序遍历二叉树:\n");
Post_order(T);
printf("\n\nOK!");
return 0;
}