二叉树建立和遍历

来源:互联网 发布:荣誉勋章2010优化 编辑:程序博客网 时间:2024/06/05 02:35
#include "stdio.h"#include "string.h"#include "malloc.h"#define NULL 0typedef 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 0
原创粉丝点击