二叉树的先序中序后序以及递归算法求高度和结点数目

来源:互联网 发布:入骨相思知不知福禄 编辑:程序博客网 时间:2024/04/20 19:44
#include "stdio.h"//定义结点typedef struct Node{    char data;    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)->data=ch;        CreateBiTree(&((*bt)->LChild));        CreateBiTree(&((*bt)->RChild));    }}//先序遍历二叉树void PreOrder(BiTree root){    if(root!=NULL)    {        printf("%c ",root->data);//访问根结点        PreOrder(root->LChild);//先序遍历左子树        PreOrder(root->RChild);//先序遍历右子树    }}//中序遍历二叉树void InOrder(BiTree root){    if(root!=NULL)    {        InOrder(root->LChild);//中序遍历左子树        printf("%c ",root->data);//访问根结点        InOrder(root->RChild);//中序遍历右子树    }}//后序遍历二叉树void PostOrder(BiTree root){    if(root!=NULL)    {        PostOrder(root->LChild);//后序遍历左子树        PostOrder(root->RChild);//后序遍历右子树        printf("%c ",root->data);//访问根结点    }}//先序遍历输出二叉树的结点void PreOrder1(BiTree root) //先序遍历输出二叉树的结点,为指向二叉树根结点的指针{    if(root!=NULL)    {        printf("%c ",root->data);//输出根结点        PreOrder1(root->LChild);//先序遍历左子树        PreOrder1(root->RChild);//先序遍历右子树    }}//后序遍历统计二叉树的结点的个数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)   //后序遍历求二叉树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;//如果是空树,则返回0}//主函数输出int main(){    printf("请输入二叉树:\n");    BiTree root;    CreateBiTree(&root);    printf("先序遍历:\n");//输出先序遍历的结果    PreOrder(root);    printf("\n中序遍历:\n");//输出中序遍历的结果    InOrder(root);    printf("\n后序遍历:\n");//输出后序遍历的结果    PostOrder(root);    printf("\n输出叶子结点:\n");//输出叶子结点    PreOrder1(root);    leaf(root);    printf("\n输出叶子结点数目:\n%d",leaf(root));//输出叶子结点的数目    PostTreeDepth(root);    printf("\n输出二叉树的高度:\n%d",PostTreeDepth(root));//输出二叉树的高度}//下面是二叉树的输入/*ABDE..F...CGI...HJ..K.L..*/

阅读全文
0 0
原创粉丝点击