二叉树遍历

来源:互联网 发布:矩阵图怎么做 编辑:程序博客网 时间:2024/06/13 07:15
#include<stdio.h>

//定义节点类型
typedef struct node                   //定义节点类型
{
    char date;                        //根
    struct node * LChild;             //左孩子指针
    struct node * RChild;             //右孩子指针

}BTnode,*BiTree;


//创建一个新的二叉树
void CreateBiTree(BiTree * bitree)
{
    char c = getchar();
    if(c=='.')
    {
        *bitree=NULL;
    }
    else
    {
        (*bitree)=(BiTree)malloc(sizeof(BTnode));//建立一个新结点(*bitree
        /* 给根,左,右传参*/
        (*bitree)->date = c;
        CreateBiTree(&((*bitree)->LChild));     //指针传参取地址
        CreateBiTree(&((*bitree)->RChild));
    }
}


//先序遍历
void PreOrder(BiTree root)
{
    if (root != NULL)
    {
        printf("%c",root->date);          //访问根结点
        PreOrder(root->LChild);          //遍历左子树
        PreOrder(root->RChild);          //遍历右子树
    }

}

//中序遍历

void Inorder(BiTree root)
{
    if(root != NULL)
    {
        Inorder(root->LChild);       //左
        printf("%c",root->date);     //根
        Inorder(root->RChild);       //右
    }
}



//后序遍历
void PostOrder(BiTree root)
{
    if(root !=NULL)
    {
        PostOrder(root->LChild);      //左
        PostOrder(root->RChild);      //右
        printf("%c",root->date);      //根
    }
}

int main()
{

        BiTree tree;
        CreateBiTree(&tree);
        PreOrder(tree);
        Inorder(tree);
        PostOrder(tree);


}


















原创粉丝点击