二叉树

来源:互联网 发布:jquery调用js函数 编辑:程序博客网 时间:2024/06/06 03:40
#include<stdio.h>
//定义二叉树结点结构
typedef struct Node
{
    char date;
    struct Node * LChild;
    struct Node * RChild;
}BiTNode,*BiTree;
//二叉树的初始化
void CreateBiTree(BiTree *bt)
{
    char ch;
    ch = getchar();
    if(ch == '.')
    {
        *bt= NULL;
    }


    else
    {
        *bt = (BiTree)malloc(sizeof(BiTNode));//申请空间
        (*bt)->date = ch;
        CreateBiTree(&((*bt)->LChild));
        CreateBiTree(&((*bt)->RChild));
    }
}
//先序遍历二叉树
void PreOrder(BiTree root)
{
    if(root)
    {
        printf("%c\n",root->date);
        PreOrder(root->LChild);
        PreOrder(root->RChild);
    }
}
//中序遍历
void InOrder(BiTree root)
{
   if(root!=NULL)
   {
       InOrder(root->LChild);
       printf("%c\n",root->date);
       InOrder(root->RChild);
   }
}
//后序遍历
void PostOrder(BiTree root)
{
    if(root!=NULL)
   {
       PostOrder(root->LChild);
       PostOrder(root->RChild);
       printf("%c\n",root->date);
   }
}
//求叶子结个数(后序)
int leaf(BiTree root)
{
    int LeafCount;
    if(root == NULL)
        LeafCount = 0;
    else if((root->LChild==NULL)&&(root->RChild==NULL))
        LeafCount=1;
    else
        LeafCount=leaf(root->LChild)+leaf(root->RChild);
    return LeafCount;
}
//后序遍历求二叉树高度
int PostTreeDepth(BiTree bt)
{
    int hl,hr,max;
    if(bt!=NULL)
    {
        hl=PostTreeDepth(bt->LChild);
        hr=PostTreeDepth(bt->RChild);
        max=hl>hr?hl:hr;
        return(max+1);
    }
    else return(0);
}
int main()
{
    BiTree root;
    CreateBiTree(&root);
    printf("先序\n");
    PreOrder(root);
    printf("中序\n");
    InOrder(root);
    printf("后序\n");
    PostOrder(root);
    printf("叶子结点个数\n");
    printf("%d\n",leaf(root));
    printf("树的高度");
    printf("%d\n",PostTreeDepth(root));
}
原创粉丝点击