C語言資料結構——求二叉樹葉子結點個數
阿新 • • 發佈:2018-12-26
小編儲存了不少程式碼,最近新開通了CSDN部落格,以前一直看到別人的程式碼分享,深受啟發,非常感謝,所以小編現在也要將自己的程式碼分享給大家,希望大家可以與瀟小白一起在程式設計的道路上越走越遠,早日成為大佬!雖然我目前只是一名大二的學生,不過我會努力噠!加油!
本次分享的用C語言求二叉樹葉子節點的個數,由於程式碼比較簡單,瀟小白本次就設定了一個C檔案,不是以前的工程檔案,小夥伴們執行時要注意哦!
程式碼如下:
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
typedef char ElemType;
typedef struct node
{
ElemType data; // 資料元素
struct node *lchild; //指向左孩子
struct node *rchild; //指向右孩子
}*BitTree;
void CreatBiTree(BitTree *bt)
{
char ch;
ch=getchar();
if(ch=='#')
*bt=NULL;
else
{
*bt=(BitTree)malloc(sizeof(BitTree));
(*bt)->data=ch;
CreatBiTree(&((*bt)->lchild)) ;
CreatBiTree(&((*bt)->rchild));
}
}
int CountLeaf(BitTree *bt,int count)
{
if((*bt)!=NULL)
{
if((*bt)->lchild==NULL&&(*bt)->rchild==NULL)
count++;
count=CountLeaf(&(*bt)->lchild,count);
count=CountLeaf(&(*bt)->rchild,count) ;
}
return count;
}
void main()
{
int count=0;
BitTree tree;
printf("請輸入二叉樹(以#為空子樹):");
CreatBiTree(&tree);
count=CountLeaf(&tree,count);
printf("葉子節點數為:%d",count);
printf("\n");
}
執行結果看這裡: