标题:先序、中序、后序遍历的递归算法
只看楼主
srgzyq
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-5-9
 问题点数:0 回复次数:3 
先序、中序、后序遍历的递归算法
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define OK 1
#define ERROR 0
#define NULL 0
#define OVERFLOW -2

typedef int Status;
typedef char TElemType;

/*二叉树的二叉链表存储表示*/
typedef struct BiTNode{
    TElemType data;
    struct BiTNode *lchild, *rchild;    //左右孩子指针
}BiTNode, *BiTree;

/*建立二叉链表*/
Status CreateBiTree(BiTree &T){
    //按先序次序输入二叉树中结点值,空格表示空树
    //构造二叉链表表示的二叉树
    char ch;
    scanf("%c",&ch);
    
    //ch=getchar();
    if(ch==' ')
        T=NULL;
        
    else
    {
        if(!(T=(BiTNode*)malloc(sizeof(BiTNode)))) exit(OVERFLOW);
        T->data=ch;
        CreateBiTree(T->lchild);
        CreateBiTree(T->rchild);
    }
    return OK;
}

/*打印二叉树的内容*/
Status PrintElement(char ch)
{
    printf("%c",ch);

    return OK;
}

/*先序遍历二叉树,递归算法*/
Status PreOrderTraverse(BiTree T,Status(*PrintElement)(TElemType e))
{
    if(T)
    {
        if(PrintElement(T->data))
            if(PreOrderTraverse(T->lchild,PrintElement))
                if(PreOrderTraverse(T->rchild,PrintElement))
                    return OK;
        return ERROR;
    }
    else return OK;
}
/*中序遍历二叉树,递归算法*/
Status InOrderTraverse(BiTree T,Status(*PrintElement)(TElemType e))
{
    if(T)
    {
        if(InOrderTraverse(T->lchild,PrintElement))
            if(PrintElement(T->data))
                if(InOrderTraverse(T->rchild,PrintElement))
                    return OK;
        return ERROR;
    }
    else return OK;
}

/*后序遍历二叉树,递归算法*/
Status PostOrderTraverse(BiTree T,Status(*PrintElement)(TElemType e))
{
    if(T)
    {
        if(PostOrderTraverse(T->lchild,PrintElement))
            if(PostOrderTraverse(T->rchild,PrintElement))
                if(PrintElement(T->data))
                    return OK;
        return ERROR;
    }
    else return OK;
}


int main()
{    BiTree T;
    printf("请输入二叉树:");
    printf("\n");
    CreateBiTree(T);
    
    printf("先序遍历:");
    printf("\n");
    PreOrderTraverse(T,PrintElement);
    
    printf("\n");
    printf("中序遍历:");
    printf("\n");
    InOrderTraverse(T,PrintElement);
    
    printf("\n");
    printf("后序遍历:");
    printf("\n");
    PostOrderTraverse(T,PrintElement);
    printf("\n");
    return 0;

}
搜索更多相关主题的帖子: 遍历 递归 算法 
2008-05-14 09:31
srgzyq
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2008-5-9
得分:0 
可以输入 ABC##DE#G##F###
进行测试 注"#"为空格
2008-05-14 09:32
wonderyude
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2007-4-16
得分:0 
good
2008-11-26 19:22



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-214199-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.115922 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved