二叉树

来源:互联网 发布:oracle linux 启动命令 编辑:程序博客网 时间:2024/06/05 13:26
#include<stdio.h>typedef struct Node{    char data;    struct Node * LChild;    struct Node * RChild;}BiTNode, *BiTree;void CreateBiTree(BiTree *bitree){    char c;    c=getchar();    if(c=='.')        *bitree=NULL;    else{    *bitree=(BiTree)malloc(sizeof(BiTNode));      (*bitree)->data=c;      CreateBiTree(&((*bitree)->LChild));      CreateBiTree(&((*bitree)->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)/* 后序遍历二叉树,root为指向二叉树(或某一子树)根结点的指针*/{if(root!=NULL){    PostOrder(root ->LChild); /*后序遍历左子树*/    PostOrder(root ->RChild); /*后序遍历右子树*/    printf("%c",root ->data);       /*访问根结点*/}}int PostTreeDepth(BiTree bitree)   /* 后序遍历求二叉树bt高度的递归算法 */{  int hl, hr, max;  if(bitree!=NULL)  {       hl=PostTreeDepth(bitree->LChild);  /* 求左子树的深度 */       hr=PostTreeDepth(bitree->RChild);  /* 求右子树的深度 */       max=hl>hr?hl:hr;              /* 得到左、右子树深度较大者*/        return(max+1);                /* 返回树的深度 */    }  else return(0);             /* 如果是空树,则返回0 */   }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 main(){    BiTree bitree;    CreateBiTree(&bitree);    printf("PreOrder:\n");    PreOrder(bitree);    printf("\nInOrder:\n");    InOrder(bitree);    printf("\nPostOrder:\n");    PostOrder(bitree);    printf("\nPostTreeDepth:");    printf("%d",PostTreeDepth(bitree));    printf("\nleaf:");    printf("%d",leaf(bitree));    return 0;}/*ABDE..F...CGI...HJ..K.L..*/

原创粉丝点击