二叉树

来源:互联网 发布:数据交换共享 编辑:程序博客网 时间:2024/06/03 21:18

三种方法遍二叉树

求叶子结点和叶子结点数目

求树的高度


代码:
#include<stdio.h>
typedef struct Node{
    char data;
    struct Node *LChild;
    struct Node *RChild;
}BiTNode,*BiTree;
/*用扩展先序遍历序列创建二叉链表*/
void CreateBiTree(BiTree *bitree){
     char 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){
    /*先序遍历二叉树, root为指向二叉树(或某一子树)根结点的指针*/
    if(root != NULL){
        printf("%c",root->data);       /*输出根节点*/
        PreOrder(root->LChild);   /*先序遍历左子树*/
        PreOrder(root->RChild);   /*先序遍历右子树*/
    }
}

InOrder(BiTree root)
/*中序遍历二叉树, 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);       /*访问根结点*/
 }
}
//输出二叉树中的叶子结点
/*先序遍历输出二叉树中的叶子结点。root为指向二叉树根节点的指针*/
void PreOrder1(BiTree root)
{
    if(root!=NULL)
    {
        if(root->LChild==NULL && root->RChild==NULL)
        printf("%c",root->data);
        PreOrder(root->LChild);
        PreOrder(root->RChild);
    }
}
/*LeafCount为保存叶子结点数目的全局变量,调用之前初始化为0*/
int leaf(BiTree root)
{
    int LeafCount=0;
    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()
{
    BiTree tree;
    CreateBiTree(&tree);
    printf("先序遍历为:\n");
    PreOrder(tree);
    printf("\n");
    printf("中序遍历为:\n");
    InOrder(tree);
    printf("\n");
    printf("后序遍历为:\n");
    PostOrder(tree);
    printf("\n");
    printf("叶子结点\n");
    PreOrder1(tree);
    printf("\n");
    printf("叶子结点数目为:%d\n",leaf(tree));
    printf("\n");
    printf("树的高度为:%d",PostTreeDepth(tree));
    return 0;
}

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

原创粉丝点击