当前位置:编程学习 > C/C++ >>

C语言二叉树递归(前序中序后序)

三个都要高手帮忙
答案:希望对你有帮助 自己以前练习 的

//中序遍历1
 void zhongxu(BiTree T){
    if(T->lchild){                //如果有左孩子
     if( T->lchild->lchild){        //如果有左孩子的左孩子 
       zhongxu(T->lchild);        //遍历他的左孩子 
     }
     printf("%d\n",T->lchild->data);       //如果没有左孩子的左孩子就打印他的左孩子的值 
    }
    printf("%d\n",T->data);          //如果没有左孩子就打印他的值
    if(T->rchild)
    zhongxu(T->rchild);

  }
//中序遍历2
   void zhongxu(BiTree T){
        if(T){
             houxu2(T->lchild);
       printf("%d\n",T->data);
        houxu2(T->rchild);
        }
   }


//前序遍历1
  void qianxu(BiTree T){
    if(T)       //如果存在节点T  
    printf("%d\n",T->data);  //打印出T的数值
    if(T->lchild)   //如果T有左孩子
        qianxu(T->lchild);  //遍历左孩子
    if(T->rchild)   //如果有右孩子
        qianxu(T->rchild);  //遍历右孩子
  }
//前序遍历2
   void qianxu(BiTree T){
        if(T){
             printf("%d\n",T->data);
      houxu2(T->lchild);
        houxu2(T->rchild);
        }
   }


 
//后序遍历
   void houxu(BiTree T){
        if(T){
             houxu2(T->lchild);
             houxu2(T->rchild);
       printf("%d\n",T->data);
        }
   }

/******************************************************/
/*       二叉树的建立深度优先遍历求叶子个数求深度        */
/******************************************************/

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define NULL 0
typedef struct bitnode{
    int data;
    struct bitnode *lchild,*rchild;
}bitnode,*bitree;
/*创建一个二杈树以#号结束*/
bitree create(bitree t){
    char ch;
    ch=getchar();
    if(ch=='#')
        t=NULL;
    else{
        t=(bitree)malloc(sizeof(bitnode));
        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);
        /*printf("%c",t->data); 中序*/
        preorder(t->rchild);
        /*printf("%c",t->data); 后序*/
    }
}
/*求深度*/
int depth(bitree t){
    int depthval,depl,depr;
    if(!t)
        depthval=0;
    else{
        depl=depth(t->lchild);
        depr=depth(t->rchild);
        depthval=1+(depl>depr?depl:depr);
    }
    return depthval;
}

/*求叶子数*/
int countleaf(bitree t){
    int count=0;
    if(!t)
        count=0;
    else if((!t->lchild)&&(!t->rchild))
        count++;
    else
        count=countleaf(t->lchild)+countleaf(t->rchild);
    return count;

}
/*主函数*/
main(){
    bitree t=NULL;
    printf("\nplease input a tree:");
    t=create(t);
    preorder(t);
    printf("\ndepth:%d\nleave:%d\n",depth(t),countleaf(t));
    system("pause");
}

上一个:2008年全国计算机二级c语言考试大纲是什么
下一个:软件是用C语言程序开发出来的。C语言用什么开发呢?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,