C语言实现对二叉树的操作
C语言实现对二叉树的操作
代码思想:
(1)生成二叉树:采用先序遍历的方式创建二叉树;
(2)先序遍历:首先访问根节点,然后按照先序遍历的方式访问左子树,再按照先序遍历的方式访问右子树。
(3)中序遍历:首先按照中序遍历方式访问左子树,然后访问根节点,再按照中序遍历访问右子树;
(4)后序遍历:首先按照后序遍历的方式访问左子树,再按照后序遍历的方式访问右子树,最后访问根节点;
(5)计算二叉树深度:通过遍历二叉树的左子树和右子树深度,然后比较左子书和右子树的大小,返回大的深度;
(6)计算叶子节点个数:通过先序遍历二叉树,当子节点为0时,叶子结点数加1;
代码实现的功能:
1.先序遍历 2.中序遍历 3.后序遍历 4.计算叶子节点个数 5.计算二叉树深度
代码内容:
#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"
typedef struct BTNode
{
int data;
struct BTNode *Lchild,*Rchild;
}BTree;
//初始化
BTree * Ini_BTNode()
{
BTree *bt ;
int a;
bt=(BTree *)malloc(sizeof(BTree));
printf("输入根节点:(0表示空树)\n");
scanf("%d",&a);
if(a==0)
{
printf("这是空树!");
exit(0);
}
bt->data=a;
bt->Lchild=NULL; //左子树节点
bt->Rchild=NULL; //右子树节点
return bt;
}
int creat_BiTree(BTree *bt)//输入左子树
{
int a;
BTree *Node;
printf("请输入%d节点的左孩子(0为空)\n",bt->data) ;
scanf("%d",&a);
if(a!=0)
{
Node=(BTree*)malloc(sizeof(BTree));
Node->data=a;
Node->Lchild=NULL;
Node->Rchild=NULL;
bt->Lchild=Node;
creat_BiTree(bt->Lchild);
}
printf("请输入%d节点的右孩子(0为空)\n",bt->data) ; //输入右子树
scanf("%d",&a);
if(a!=0)
{
Node=(BTree *)malloc(sizeof(BTree));
Node->data=a;
Node->Lchild=NULL;
Node->Rchild=NULL;
bt->Rchild =Node;
creat_BiTree(bt->Rchild);
}
return 0;
}
void PerOrderTraverse(BTree *bt) //先序遍历
{
if(bt!=NULL)
{
printf("%d -->",bt->data);
PerOrderTraverse(bt->Lchild);
PerOrderTraverse(bt->Rchild);
}
}
void InOrderTraverse(BTree *bt) //中序遍历
{
if(bt!=NULL)
{
InOrderTraverse(bt->Lchild);
printf("%d -->",bt->data);
InOrderTraverse(bt->Rchild);
}
}
void PostOrderTraverse(BTree *bt) //后序遍历
{
if(bt!=NULL)
{
PostOrderTraverse(bt->Lchild);
PostOrderTraverse(bt->Rchild);
printf("%d -->",bt->data);
}
}
int LeafCount(BTree *bt)
{
static int count;
if (bt != NULL)
{
if (bt->Lchild == NULL && bt->Rchild == NULL)
{
count++;
}
LeafCount(bt->Lchild);
LeafCount(bt->Rchild);
}
return count;
}
int TreeDeep(BTree *bt)
{
int deep = 0;
if (bt != NULL)
{
int leftdeep = TreeDeep(bt->Lchild);
int rightdeep = TreeDeep(bt->Rchild);
deep = leftdeep >= rightdeep?leftdeep+1:rightdeep+1;
}
return deep;
}
main()
{
BTree *bt;
int a,leafCount,depth;
printf("\t\t**************** 二叉树操作 ****************\n\n");
bt=Ini_BTNode();creat_BiTree(bt);
printf("以%d为根的树创建成功!\n",bt->data);
while(1)
{
printf("1. 先序遍历\n");
printf("2. 中序遍历\n");
printf("3. 后序遍历\n");
printf("4.计算叶子节点个数\n");
printf("5.计算二叉树深度\n");
printf("6. 退出程序\n");
printf("请选择:");
scanf("%d",&a);
switch(a)
{
case 1:
printf("先序遍历\n");
PerOrderTraverse(bt);
printf("\n");
break;
case 2:
printf("中序遍历\n");
InOrderTraverse(bt);
printf("\n");
break;
case 3:
printf("后序遍历\n");
PostOrderTraverse(bt);
printf("\n");
break;
case 4:
leafCount = LeafCount(bt);
printf("叶子节点个数:%d\n",leafCount);
printf("\n");
break;
case 5:
depth = TreeDeep(bt);
printf("树的深度为:%d\n",depth);
printf("\n");
break;
case 6:
exit(0);
default:
printf("输入错误");
}
}
}
博客园:https://www.cnblogs.com/newtol
微信公众号:Newtol
【转发请务必保留原作者,否则保留追责权利】