二叉树的递归实现及递归遍历

来源:互联网 发布:最新wifi破解软件 编辑:程序博客网 时间:2024/05/04 08:00
#include
#include

//定义节点 
typedef struct BiNode{
       char data;
       struct BiNode *lch;
       struct BiNode *rch;
}BiNode,*BiTree;

//先序拓展序列建立二叉树 
void Create(BiTree &T)
{
       T =(BiNode*) malloc (sizeof(BiNode));
       
       printf("Enter the data \n");
       scanf(" %c",&T->data);
       if(T->data=='#') T = NULL;
       if(T){
              printf("");
              Create(T->lch);
              Create(T->rch);
       }
}

//先序遍历 (递归)
void Preorder (BiTree T)
{                 
   if (T) {
     printf(" %c",T->data);           // 访问根结点
     
     Preorder(T->lch); // 遍历左子树
     Preorder(T->rch);// 遍历右子树
   }
}

//中序遍历 (递归)
void Inorder (BiTree T)
{
     if(T){
      Inorder(T->lch);
      
      printf(" %c",T->data);
      
      Inorder(T->rch);   
      }

//后序遍历 (递归)
void Postorder (BiTree T)
{
     if(T){
      Postorder(T->lch);
      Postorder(T->rch);
      
      printf(" %c",T->data); 
    }

int main()
{
   //建树 
    printf("The fuctionCreate() is called.\n");
    BiTree T;
    Create(T);
    
   //三种遍历递归算法 
    printf("\n");   
    printf("The fuctionPreorder() is called.\n");
    Preorder(T);
    
    printf("\n");
    printf("The fuctionInorder() is called.\n");
    Inorder(T);
    
    printf("\n");
    printf("The fuctionPostorder() is called.\n");
    Postorder(T);
    
    
    printf("\n");
    system("pause");
    
}
原创粉丝点击