二叉树

来源:互联网 发布:淘宝网品牌羽绒服 编辑:程序博客网 时间:2024/06/05 22:39
#include<stdio.h>
//二叉链表结点结构
typedef struct Node
{
    int 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!=NULL)
{
      printf("%c",root->date);
  PreOrder(root->LChild);
  PreOrder(root->RChild);
}
   }


void  InOrder(BiTree root)
/*中序遍历二叉树, root为指向二叉树(或某一子树)根结点的指针*/
{ if (root!=NULL)
{
    InOrder(root->LChild);   /*中序遍历左子树*/
    printf("%c",root->date);        /*访问根结点*/
    InOrder(root->RChild);   /*中序遍历右子树*/
}
   }


void  PostOrder(BiTree root)
/* 后序遍历二叉树,root为指向二叉树(或某一子树)根结点的指针*/
{ if(root!=NULL)
{
    PostOrder(root ->LChild); /*后序遍历左子树*/
    PostOrder(root ->RChild); /*后序遍历右子树*/
    printf("%c",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;
}


/* 后序遍历求二叉树bt高度的递归算法 */
 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);             /* 如果是空树,则返回0 */
}




int main()
{
    BiTree tree;
    CreateBiTree(&tree);


    printf("PreOrder:\n");
    PreOrder(tree);
    printf("\n");
    printf("InOrder:\n");
    InOrder(tree);
    printf("\n");
    printf("PostOrder:\n");
    PostOrder(tree);
    printf("\n");
    printf("LeafCount:");
    printf("%d\n",leaf(tree));
    printf("\n");
    printf("PostTreeDepth:");
    printf("%d\n",PostTreeDepth(tree));


    return 0;


}


//ABDE..F...CGI...HJ..K.L...