【二叉樹】SDUT 3342 資料結構實驗之二叉樹三:統計葉子數
阿新 • • 發佈:2018-11-26
Problem Description
已知二叉樹的一個按先序遍歷輸入的字元序列,如abc,,de,g,,f,,, (其中,表示空結點)。請建立二叉樹並求二叉樹的葉子結點個數。
Input
連續輸入多組資料,每組資料輸入一個長度小於50個字元的字串。
Output
輸出二叉樹的葉子結點個數。
Sample Input
abc,,de,g,,f,,,
Sample Output
3
#include <stdio.h> #include <stdlib.h> typedef struct no { char data; struct no *lc,*rc; } node; int l; node *creat(char a[]) { char c; node *root; if(!a[l]) return NULL; root=(node*)malloc(sizeof(node)); c=a[l++]; if(c==',')return NULL; root->data=c; root->lc=creat(a); root->rc=creat(a); return root; } int cnt; void ye(node *root) { if(root) { if(!root->lc&&!root->rc) cnt++; else { ye(root->lc); ye(root->rc); } } } int main() { char a[60]; node *root; while(~scanf("%s",a)) { l=0; root=creat(a); cnt=0; ye(root); printf("%d\n",cnt); } return 0; }