二叉树递归遍历 - 先序 中序 后序

#include <stdio.h>
#include <stdlib.h>

typedef struct BTNode
{
    char data;
    struct BTNode *left;
    struct BTNode *right;
}BTNode;

//先序遍历建立二叉树
void CreateBiTree(BTNode *&T)
{
    char c;
    scanf("%c",&c);
    if(c=='#')
        T = NULL;
    else
    {
        T = (BTNode *)malloc(sizeof(BTNode));
        T->data = c;
        CreateBiTree(T->left);
        CreateBiTree(T->right);
    }
}

void preOrder(BTNode *T)
{
    if(T!=NULL)
    {
        printf("%c ",T->data);
        preOrder(T->left);
        preOrder(T->right);
    }
}
void inOrder(BTNode *T)
{
    if(T!=NULL)
    {
        inOrder(T->left);
        printf("%c ",T->data);
        inOrder(T->right);
    }
}

void postOrder(BTNode *T)
{
    if(T!=NULL)
    {
        postOrder(T->left);
        postOrder(T->right);
        printf("%c ",T->data);
    }
}

int main()
{
    BTNode *T;
    CreateBiTree(T);
    preOrder(T);
    printf("\n");
    inOrder(T);
    printf("\n");
    postOrder(T);
    printf("\n");
    //先序建立二叉树 ABC##DE##F##GH### p142
    system("pause");
    return 0;
}

测试

ABC##DE##F##GH###
A B C D E F G H
C B E D F A H G
C E F D B H G A

    原文作者:Co_zy
    原文地址: https://www.jianshu.com/p/be8a9a5a0a26
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞