二叉樹的建立

#include "stdio.h"
#include "string.h"
#include "BiTNode.h"




 //先序建立二叉樹
BiTree ProCreate(BiTree T)
{
   char ch;
   scanf("%c", &ch);
   if(ch == '#')
   {
        T = NULL;
        return NULL;
   }


   else
   {
       T = (BiTNode *)malloc(sizeof(BiTNode));
       if(!T)
       {
            printf("Error!");
            return NULL;
       }


       T->data = ch;
       T->lchild = ProCreate(T->lchild);
       T->rchild = ProCreate(T->rchild);
   }
   return T;
}
//先序遍歷二叉樹
void Preorder(BiTree T)
{
  if(T)
  {
       printf("%c", T->data);
       Preorder(T->lchild);
       Preorder(T->rchild);
  }
}


//中序遍歷二叉樹
void Inorder(BiTree T)
{
   if(T)
   {
       Inorder(T->lchild);
       printf("%c",T->data);
       Inorder(T->rchild);
   }
}
 //後序遍歷二叉樹
void Postorder(BiTree T)
{
    if(T)
    {
        Postorder(T->lchild);
        Postorder(T->rchild);
        printf("%c",T->data);
    }
}
 //求葉子節點的個數
int Sumleaf(BiTree T)
{
      int sum = 0, m, n;
      if(T)
      {
           if((!T->lchild) && (!T->rchild))
                sum ++;
           m = Sumleaf(T->lchild);
           sum += m;
           n = Sumleaf(T->rchild);
           sum += n;
      }
      return sum;
}
//求二叉樹的深度
int Depth(BiTree T)
{
      int dep = 0, depl, depr;
      if(!T) dep = 0;
      else
      {
           depl=Depth(T->lchild);
           depr=Depth(T->rchild);
           dep=1+(depl>depr?depl:depr);
      }
      return dep;
}


int main()
{
    BiTree T;
    int sum, dep;
    printf("先序創建二叉樹,請輸入序列,空使用#代替 \n");
    T = ProCreate(T);
    printf("先序遍歷的結果: ");
    Preorder(T);
    printf("\n中序遍歷的結果: ");
    Inorder(T);
    printf("\n後序遍歷的結果: ");
    Postorder(T);
    printf("\n葉子個數: ");
    sum=Sumleaf(T);
    printf("%d",sum);
    dep=Depth(T);
    printf("\n深度爲:%d \n",dep);
    return 0;

}


BiTNode.h的內容

#ifndef BITNODE_H_INCLUDED
#define BITNODE_H_INCLUDED
#define ElemType char


 //定義數據結構
typedef struct BiTNode
{
    ElemType data;
    struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;






#endif // BITNODE_H_INCLUDED

發佈了16 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章