二叉树的遍历

来源:互联网 发布:网络有什么坏处 编辑:程序博客网 时间:2024/05/23 16:51
#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);
    }
}
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);
    }
}
void main()
{
    BiTree T;
    printf("请输入数据:\n");
    T=Create(T);
    printf("先序遍历为:\n");
    Preorder(T);
    printf("中序遍历为:\n");
    zhongxu(T);
    printf("后序遍历为:\n");
    houxu(T);
    printf("\n");
}
0 0
原创粉丝点击