#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
typedef struct Node/*类型定义*/
{
int data;
Node * LChild;
Node * RChild;
}BiTree;
BiTree * CreateBiTree(BiTree * bt)/*先序创建二叉树*/
{
char ch;
ch=getchar();
if(ch=='.')
{
bt=NULL;
}
else
{
bt=(BiTree *)malloc(sizeof(BiTree));
bt->data=ch;
bt->LChild=CreateBiTree(bt->LChild);
bt->RChild=CreateBiTree(bt->RChild);
}
return bt;
}
void PreOrder(BiTree * bt)/*先序遍历二叉树*/
{
if(bt)
{
printf("%c",bt->data);
PreOrder(bt->LChild);
PreOrder(bt->RChild);
}
}
void ZhongOrder(BiTree * bt)/*中序遍历二叉树*/
{
if(bt)
{
PreOrder(bt->LChild);
printf("%c",bt->data);
PreOrder(bt->RChild);
}
}
//统计叶子节点个数算法1
int totalLeaf1(BiTree * bt)
{
int sum=0,m,n;
if(bt!=NULL)
{
if(bt->LChild==NULL && bt->RChild==NULL)
sum++;
m=totalLeaf1(bt->LChild);
sum+=m;
n=totalLeaf1(bt->RChild);
sum+=n;
}
return sum;
}
//统计叶子节点个数算法1
int totalLeaf2(BiTree * bt)
{
int sum;
if(bt==NULL)
sum = 0;
else if(bt->LChild==NULL && bt->RChild==NULL)
sum = 1;
else
{
sum=totalLeaf2(bt->LChild)+totalLeaf2(bt->RChild);
}
return sum;
}
//树的深度
int BtDepth(BiTree * bt)
{
int depth,depthl,depthr;
if(bt==NULL)
depth=0;
else
{
depthl=BtDepth(bt->LChild);
depthr=BtDepth(bt->RChild);
depth=1+(depthl>depthr?depthl:depthr);
}
return depth;
}
//按树状打印
void printTree(BiTree * bt,int depth)
{
if(bt==NULL)
return;
printTree(bt->RChild,depth+1);//打印右子树
for(int i=0;i<depth;i++)
printf(" ");
printf("%c\n",bt->data);
printTree(bt->LChild,depth+1);//打印左子树
}
void main()/*主入口*/
{
BiTree * bt;
printf("创建二叉树:"); bt=CreateBiTree(bt);
printf("先序遍历:"); PreOrder(bt); printf("\n");
printf("中序遍历:"); ZhongOrder(bt); printf("\n");
printf("树深度:%d\n",BtDepth(bt));
printTree(bt,3);
}
/*
#include "malloc.h"
#include "stdio.h"
#include "string.h"
#define NULL 0
typedef struct BiTNode{ //类型定义
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Create(BiTree T){ //创建
char ch;
ch=getchar();
if(ch=='#')
T=NULL;
else{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
printf("Error!");
T->data=ch;
T->lchild=Create(T->lchild);
T->rchild=Create(T->rchild);
}
return T;
}
void Preorder(BiTree T){ //先序遍历
if(T){
printf("%c",T->data);
Preorder(T->lchild);
Preorder(T->rchild);
}
}
int Sumleaf(BiTree T){ //叶子节点个数
int sum=0,m,n;
if(T){
if((!T->lchild)&&(!T->rchild))
sum++;
m=Sumleaf(T->lchild);
sum+=m;
n=Sumleaf(T->rchild);
sum+=n;
}
return sum;
}
void zhongxu(BiTree T){ //中序遍历
if(T){
zhongxu(T->lchild);
printf("%c",T->data);
zhongxu(T->rchild);
}
}
void houxu(BiTree T){ //后序遍历
if(T){
houxu(T->lchild);
houxu(T->rchild);
printf("%c",T->data);
}
}
int Depth(BiTree T){ //树的深度
int dep=0,depl,depr;
if(!T) dep=0;
else{
depl=Depth(T->lchild);
depr=Depth(T->rchild);
dep=1+(depl>depr?depl:depr);
}
return dep;
}
main(){ //主程序入口
BiTree T;
int sum,dep;
T=Create(T);
Preorder(T);
printf("\n");
zhongxu(T);
printf("\n");
houxu(T);
printf("\n");
sum=Sumleaf(T);
printf("%d",sum);
dep=Depth(T);
printf("\n%d",dep);
}
*/
二叉树相关操作
最新推荐文章于 2022-11-11 21:52:14 发布