二叉树建立和遍历

#include "stdio.h"
#include "string.h"
#include "malloc.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;
}

void 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);
} 

例如输入序列ABC##DE#G##F###(其中的“#”表示空,并且输入过程中不要加回车,因为回车也有对应的ASCII码,是要算字符的,但是输入 完之后可以按回车退出),这时候就能够看到结果了。
另外你必须会手动建立一棵二叉树,保证你输入的序列能构成一棵二叉树,否则你怎么输入,按最后按多少回车程序也不会结束!

原文请戳此处

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值