C 언어는 두 갈래 트리의 생성과 반복을 실현합니다 (귀속)

1805 단어
C 언어는 두 갈래 트리의 생성과 반복을 실현한다
#include <stdio.h>
typedef char ElemType;
typedef struct BiTNode
{
    ElemType data;
    struct BiTNode *lchild;
    struct BiTNode *rchild;
} BiTNode,*BiTree;

// 
void CreateBiTreeMethod1(BiTree *T);
// 
BiTree CreateBiTreeMethod2();
// 
void PreOrderTraverse(BiTree T);
// 
void InOrderTraverse(BiTree T);
// 
void PostOrderTraverse(BiTree T);

int main()
{
    BiTree T = NULL;
    //CreateBiTreeMethod1(&T);
    //PreOrderTraverse(T);
    T = CreateBiTreeMethod2();
    PreOrderTraverse(T);
    return 0;
}

// 
void CreateBiTreeMethod1(BiTree *T){
    char ch;
    scanf("%c",&ch);
    if('#' == ch){
        *T = NULL;
    }else{
        *T = (BiTree)malloc(sizeof(BiTNode));
        (*T)->data = ch;
        CreateBiTreeMethod1(&((*T)->lchild));
        CreateBiTreeMethod1(&((*T)->rchild));
    }
}

// 
BiTree CreateBiTreeMethod2(){
    char ch;
    scanf("%c",&ch);
    BiTree T;
    if('#' == ch){
        T = NULL;
    }else{
        T = (BiTree)malloc(sizeof(BiTNode));
        T->data = ch;
        T->lchild = CreateBiTreeMethod2();
        T->rchild = CreateBiTreeMethod2();
    }
    return T;
}

// 
void PreOrderTraverse(BiTree T)
{
    if(T)
    {
        printf("%c",T->data);
        PreOrderTraverse(T->lchild);
        PreOrderTraverse(T->rchild);
    }
}

// 
void InOrderTraverse(BiTree T)
{
    if(T)
    {
        PreOrderTraverse(T->lchild);
        printf("%c",T->data);
        PreOrderTraverse(T->rchild);
    }
}

// 
void PostOrderTraverse(BiTree T)
{
    if(T)
    {
        PreOrderTraverse(T->lchild);
        PreOrderTraverse(T->rchild);
        printf("%c",T->data);
    }
}

좋은 웹페이지 즐겨찾기