二叉树遍历的递归与非递归算法

来源:互联网 发布:嵌入式和单片机的区别 编辑:程序博客网 时间:2024/05/22 15:52

#include<stdio.h>
#include<stdlib.h>
typedef char datatype ;


typedef struct node
{
     datatype data;/*数据域*/
     struct node *lchild,*rchild; /*左、右孩子域*/
}BTNode;

typedef struct stack{
    BTNode *node[10] ;
    int top ;
}SStack ;

SStack * createemptyStack(){
    SStack *st = (SStack *)malloc(sizeof(SStack)) ;
    st->top = 0 ;
    return st ;
}

void push(SStack *st , BTNode *bt){
    if(st->top == 10) return ;
    st->node[st->top] = bt ;
    st->top ++ ;
}

void pop(SStack *st){
    if(st->top == 0) return ;
    st->top -- ;
}

BTNode* getTop(SStack *st){
    if(st->top == 0) return NULL ;
    return st->node[st->top - 1] ;   
}
/*---------------------------------------------------------------------------------------------------*/
/*按先序建立二叉树的二叉链表。函数的返回值指向根结点*/
BTNode* createbintree( )
{  
    char ch;
    BTNode* bt;
    ch=getchar();/*键盘上输入一个字符*/
    if (ch=='#')
        return(NULL);/*#作为结束标志*/
    else {
        bt=(BTNode*)malloc(sizeof(BTNode));/*生新结点 */
        bt->data=ch;
        bt->lchild= createbintree( );
        bt->rchild= createbintree( );
        return (bt);
    }
}
/*---------------------------------------------------------------------------------------------------*/
/*二叉树中序遍历的递归算法,t为指向根结点*/
void inorder(BTNode* t)
{
    if(t == NULL)
        return ;
    inorder(t->lchild) ;
    printf("%c " , t->data) ;
    inorder(t->rchild) ;
}
/*---------------------------------------------------------------------------------------------------*/
/*二叉树先序遍历的非递归算法,t为指向根结点*/
void  preorder(BTNode* t)
{
    SStack *st = NULL ;
    BTNode *p = NULL ;
    if(t == NULL)
        return ;
    st = createemptyStack() ;
    p = t ;
    do{
        while(p){
            printf("%c " ,p->data) ;
            if(p->rchild)
                push(st , p->rchild) ;
            p = p->lchild ;
        }
        if(st->top != 0){
            p = getTop(st) ;
            pop(st) ;
        }
    }while(st->top != 0 || p) ;
}
/*---------------------------------------------------------------------------------------------------*/
/*求以root为根的二叉树的叶子结点个数,root指向根结点,返回值为叶子结点个数*/
int leaf(BTNode* root)
{
    int leafs = 0 ;
    if(root == NULL) {
        leafs = 0 ;
    }else if(root->lchild == NULL && root->rchild == NULL)
        leafs++ ;   
    else {
        leafs += leaf(root->lchild) ;
        leafs += leaf(root->rchild) ;
    }
    return  leafs ;
}
/*---------------------------------------------------------------------------------------------------*/
void main()
{
    BTNode*bt;
    bt= createbintree( ) ;


    /*按先序遍历二叉树*/
    printf("先序遍历为:") ;
    preorder(bt) ;
    printf("/n") ;

    /*按中序遍历二叉树*/
    printf("中序遍历为:") ;
    inorder(bt) ;
    printf("/n") ;

    /*输出叶子个数*/
    printf("叶子个数为:%d /n",leaf(bt)) ;

}