关于二叉树的一些基本操作,学习总结!
如下图实现这样一个简单的二叉树创建及遍历。
****************A********************
**********B**************C**********
****D***************E********F******
*********G***************************
在程序中以‘#’代表为空。以前序遍历创建的方法则输入ABD#G###CE##F##即可实现创建如上图的二叉树。
前序遍历顺序为:ABDGCEF
中序遍历顺序为:DGBAECF
后续遍历顺序为:GDBEFCA
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef char DataType;
typedef struct Node
{
DataType data;
struct Node *lchild;
struct Node *rchild;
}BiTree;
BiTree *CreatTree() //构造二叉树
{
char a;
BiTree *new;
a = getchar();
if(a == '#') //判断是否为空
new = NULL;
else
{
new = (BiTree *)malloc(sizeof(BiTree)); //申请结点空间
new->data = a; //赋值
new->lchild = CreatTree(); //递归赋值左子树
new->rchild = CreatTree(); //递归赋值右子树
}
return new; //返回头指针
}
void preorder(BiTree *new) //前序遍历二叉树
{ if(new != NULL)
{
printf("%c\t",new->data); //访问根结点
preorder(new->lchild); //递归访问左子树
preorder(new->rchild); //递归访问右子树
}
}
void inorder(BiTree *new) //中序遍历二叉树
{
if(new != NULL)
{
inorder(new->lchild); //递归访问左子树
printf("%c\t",new->data); //访问根结点
inorder(new->rchild); //递归访问右子树
}
}
void postorder(BiTree *new) //后续遍历二叉树
{
if(new != NULL)
{
postorder(new->lchild); //递归访问左子树
postorder(new->rchild); //递归访问右子树
printf("%c\t",new->data); //访问根结点
}
}
int TreeDepth(BiTree *new) //求二叉树深度
{
int ldepth,rdepth;
if(new == NULL) //递归结束条件
return 0;
else
{
ldepth = TreeDepth(new->lchild); //左子树深度
rdepth = TreeDepth(new->rchild); //右子树深度
return (ldepth > rdepth ? ldepth+1 :rdepth+1); //返回深度最大值
}
}
int TreeNode(BiTree *new) //求二叉树的结点数
{
if(new == NULL) //递归结束条件 二叉树为空时返回0值
return 0;
else
{
return (TreeNode(new->lchild)+TreeNode(new->rchild)+1); //左子树加右子树加根结点
}
}
int TreeFnode(BiTree *new) //求二叉树叶子结点个数
{
if(new == NULL) //当二叉树为空返回0值
return 0;
else if(new->lchild == NULL && new->rchild == NULL) //当二叉树只有根结点返回1值
return 1;
else
return (TreeFnode(new->lchild)+TreeFnode(new->rchild));
//否则返回左子树右子树叶子结点的总和
}
int main()
{
int depth,node,fnode;
BiTree *root;
printf("please input BiTree data\n");
root = CreatTree(); //前序创建二叉树
preorder(root); //前序遍历
printf("\n");
inorder(root); //中序遍历
printf("\n");
postorder(root); //后续遍历
printf("\n");
depth = TreeDepth(root); //二叉树深度
printf("this bitree depth is:%d\n",depth);
node = TreeNode(root); //二叉树结点总数
printf("this bitree node number is:%d\n",node);
fnode = TreeFnode(root); //二叉树叶子结点个数
printf("this bitree foliage node number is:%d\n",fnode);
return 0;
}
如下为代码执行结果: