遍历二叉树

来源:互联网 发布:被猎头找到 知乎 编辑:程序博客网 时间:2024/06/06 07:21
#include<stdio.h>


typedef struct Node
{
    char data;
    struct Node * LChild;
    struct Node * RChild;
}BiTNode,*BiTree;


//先序遍历创建二叉链表
void CreateBiTree(BiTree *bt)
{
    char ch = getchar();
    if(ch == '.')
        *bt = NULL;
    else
    {
        *bt = (BiTree)malloc(sizeof(BiTNode));
        (*bt)->data=ch;
        CreateBiTree(&((*bt)->LChild));
        CreateBiTree(&((*bt)->RChild));
    }
}




//先序遍历二叉树
void PerOrder(BiTree root)
{
    if(root!=NULL)
    {
        print("%c",root->data);
        PreOrder(root -> LChild);
        PerOrder(root -> RChild);
    }
}


//中序遍历二叉树
void InOrder(BiTree root)
{
    if(root!=NULL)
    {
        InOrder(root->LChild);
        print("%c",root->data);
        InOrder(root->RChild);
    }
}


//后续遍历二叉树
void PostOrder(BiTree root)
{
    if(root!=NULL)
    {
        PostOrder(root->LChild);
        PostOrder(root->RChild);
        print("%c",root->data);
    }
}


//输出二叉树中的叶子节点
void LPreOrder(BiTree root)
{
    if(root!=NULL)
    {
        if(root->LChild==NULL && root->RChild==NULL)
            print(root->data);
        PreOrder(root->LChild);
        PreOrder(root->RChild);
    }
}


//统计叶子节点
void leaf(BiTree root)
{
    int LeafCount = 0;
    if(root!=NULL)
    {
        leaf(root->LChild);
        leaf(root->RChild);
        if(root->LChild==NULL && root->RChild==NULL)
            LeafCount++;
    }
}


//先序遍历二叉树高度递归算法
void PreTreeDepth(BiTree bt,int h)
{
    int depth = 0;
    if(bt!=NULL)
    {
        if(h>depth)
            depth = h;
        PreTreeDepth(bt->LChild,h+1);
        PreTreeDepth(bt->RChild,h+1);
    }
}


int main()
{
    int Case = 10;
    while(Case--)
    {
    BiTree tree;
    CreateBiTree(&tree);
    printf("PerOrder:\n");
    PerOrder(tree);
    printf("\nInOrder:\n");
    InOrder(tree);
    printf("\nPostOrder:\n");
    PostOrder(tree);
    printf("\nPreTreeDepth:\n");
    char ch = getChar();
    }
    return 0;
}
原创粉丝点击