分享

二叉树遍历

 龙驹游子 2009-06-07
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct BiTNode
{
 char data;
 struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

BiTree Create(BiTree T)
{
 char ch;
 ch=getchar();
 if(ch=='#')
 T=NULL;
 else
{
 T=(BiTNode *)malloc(sizeof(BiTNode));
 if(!T)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);
 }
}
void Inorder(BiTree T)
{
 if(T)
 {
  Inorder(T->lchild);
  printf("%c",T->data);
  Inorder(T->rchild);
 }
}
void Postorder(BiTree T)
{
 if(T)
 {
  Postorder(T->lchild);
  Postorder(T->rchild);
  printf("%c",T->data);
 }
}

int leaves(BiTree T)
{
 int sum=0,m,n;
 if(T)
{
 if((!T->lchild)&&(!T->rchild))sum++;
 m=leaf(T->lchild);
 sum+=m;
 n=leaf(T->rchild);
 sum+=n;
 }
 return sum;
}

void main()
{
 int sum;
 BiTree T;
 printf("请以先序遍历的方式输入二叉树(结点没有左右孩子时用以#表示)\n");
 T=Create(T);
 printf("先序遍历:");
 Preorder(T);
 printf("\n");
 printf("中序遍历:");
 Inorder(T);
 printf("\n");
 printf("后序遍历:");
 Postorder(T);
 printf("\n");
 printf("叶子结点个数为:\n");
 sum=leaves(T);
 printf("%d",sum);
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多