SDUT OJ 資料結構實驗之二叉樹三:統計葉子數
阿新 • • 發佈:2019-02-01
資料結構實驗之二叉樹三:統計葉子數
Time Limit: 1000 ms Memory Limit: 65536 KiBProblem Description
已知二叉樹的一個按先序遍歷輸入的字元序列,如abc,,de,g,,f,,, (其中,表示空結點)。請建立二叉樹並求二叉樹的葉子結點個數。
Input
連續輸入多組資料,每組資料輸入一個長度小於50個字元的字串。
Output
輸出二叉樹的葉子結點個數。
Sample Input
abc,,de,g,,f,,,
Sample Output
3
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char c; struct node *lt, *rt; }; char s[100]; int i,k; struct node *creat() { struct node *root; if(s[i]==','){ i++; root=NULL; } else{ root=(struct node *)malloc(sizeof(struct node)); root->c=s[i++]; root->lt=creat(); root->rt=creat(); } return root; } void num(struct node *root) { if(root){ if(!root->lt&&!root->rt){ k++; } num(root->lt); num(root->rt); } } int main() { while(~scanf("%s",s)) { i=0;k=0; struct node *root; root=creat(); num(root); printf("%d\n",k); } return 0; }