#include <stdio.h>
#include <stdlib.h>
//二叉树数据结构定义
typedef struct BiTreeNode
{
char data;
struct BiTreeNode *left;
struct BiTreeNode *right;
}BiTreeNode,*BiTree;
//二叉树的建立(先序)
void CreateBiTree(BiTree *T)
{
char val;
scanf("%c",&val);
if(val == '#')
*T = NULL; //null表示为空枝
else
{
*T = (BiTree)malloc(sizeof(BiTreeNode));
(*T)->data = val;
CreateBiTree(&(*T)->left);
CreateBiTree(&(*T)->right);
}
}
//先序遍历
void PreOrderTravel(BiTree T)
{
if(T==NULL)
return;
printf("%c ",T->data);
PreOrderTravel(T->left);
PreOrderTravel(T->right);
}
//中序遍历
void InOrderTravel(BiTree T)
{
if(T==NULL)
return;
InOrderTravel(T->left);
printf("%c ",T->data);
InOrderTravel(T->right);
}
//后序遍历
void TailOrderTravel(BiTree T)
{
if(T==NULL)
return;
TailOrderTravel(T->left);
TailOrderTravel(T->right);
printf("%c ",T->data);
}
//计算二叉树的叶子结点数
int CountLeaf(BiTree *bt,int count)
{
if((*bt)!=NULL)
{
if((*bt)->left==NULL&&(*bt)->right==NULL)
count++;
count=CountLeaf(&(*bt)->left,count);
count=CountLeaf(&(*bt)->right,count);
}
return count;
}
//求二叉树的深度
int TreeDepth(BiTree T)
{
int rightdep=0;
int leftdep=0;
if(T==NULL)
return -1;
if(T->left!=NULL)
leftdep=TreeDepth(T->left);
else
leftdep=-1;
if(T->right!=NULL)
rightdep=TreeDepth(T->right);
else
rightdep=-1;
return (rightdep>leftdep) ? rightdep+1 : leftdep+1;
}
int main()
{
printf("测试代码\n");
BiTree T;
T = (BiTree)malloc(sizeof(BiTreeNode));
printf("请给二叉树按照先序方式依次输入结点的值(空结点为#):\n");
CreateBiTree(&T);
printf("先序方式遍历结果:\n");
PreOrderTravel(T);
printf("\n");
printf("中序方式遍历结果:\n");
InOrderTravel(T);
printf("\n");
printf("后序方式遍历结果:\n");
TailOrderTravel(T);
printf("\n");
printf("输出二叉树的叶子结点数:\n");
int count = 0;
count = CountLeaf(&T, count);
printf("%d",count);
printf("\n");
printf("求二叉树的深度:\n");
int depth = 0;
depth = TreeDepth(T);
printf("%d\n",depth);
return 0;
}
二叉树的基本操作 C语言
最新推荐文章于 2024-09-05 16:04:35 发布