統(tǒng)計C語言二叉樹中葉子結點個數(shù)
樹是一種非線性的數(shù)據(jù)結構,它是由n(n>=0)個有限結點組成一個具有層次關系的集合。把它叫做樹是因
為它看起來像一棵倒掛的樹,也就是說它是根朝上,而葉朝下的,下面我們就用簡單小栗子來簡單說明關于統(tǒng)計C語言二叉樹中葉子結點個數(shù)的方法吧
簡單小栗子:
#include<stdio.h> #include<stdlib.h> ? typedef char ElemType; typedef struct BTNode { ?? ?ElemType data; ?? ?struct BTNode *left; ?? ?struct BTNode *right; }BTNode,*BiTree; ? //創(chuàng)建二叉樹 void createBTNode(BiTree &BT) { ?? ?ElemType ch; ?? ?scanf("%c",&ch); ?? ?if(ch==' ') ?? ??? ?BT=NULL; ?? ?else ?? ?{ ?? ??? ?BT = (BTNode*)malloc(sizeof(BTNode)); ?? ??? ?BT->data= ch; ?? ??? ?createBTNode(BT->left); ?? ??? ?createBTNode(BT->right); ?? ?} } ? //先序遍歷二叉樹 void printDLR(BiTree BT) { ?? ?if(BT) ?? ?{ ?? ??? ?printf("%c ",BT->data); ?? ??? ?printDLR(BT->left); ?? ??? ?printDLR(BT->right); ?? ?} } ? //統(tǒng)計二叉樹結點個數(shù) void countLeaves(BiTree BT,int &count) { ?? ?if(BT) ?? ?{ ?? ??? ?if(BT->left==NULL && BT->right==NULL) ?? ??? ?count++; ?? ??? ?else{ ?? ??? ??? ?countLeaves(BT->left,count); ?? ??? ??? ?countLeaves(BT->right,count); ?? ??? ?} ?? ?} } ? void main() { ?? ?BTNode *BT; ?? ?int count=0; ?? ?createBTNode(BT); ?? ?printf("先序遍歷:"); ?? ?printDLR(BT); ?? ?printf("\n"); ?? ?countLeaves(BT,count); ?? ?printf("二叉樹結點的個數(shù):%d\n",count); }
按照先序遍歷的方式來輸入二叉樹結點,若孩子結點為空,則輸入空格。
輸入:
ABD E CF
返回結果:
先序遍歷:
A B D E C F
二叉樹結點的個數(shù):
3
葉子結點分別是:
D、E、F
到此這篇關于統(tǒng)計C語言二叉樹中葉子結點個數(shù)的文章就介紹到這了,更多相關統(tǒng)計二叉樹中葉子結點個數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!