sdut原題鏈接
數(shù)據(jù)結(jié)構(gòu)實(shí)驗(yàn)之二叉樹三:統(tǒng)計(jì)葉子數(shù) Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 已知二叉樹的一個(gè)按先序遍歷輸入的字符序列,如abc,,de,g,,f,,, (其中,表示空結(jié)點(diǎn))。請(qǐng)建立二叉樹并求二叉樹的葉子結(jié)點(diǎn)個(gè)數(shù)。
Input 連續(xù)輸入多組數(shù)據(jù),每組數(shù)據(jù)輸入一個(gè)長(zhǎng)度小于50個(gè)字符的字符串。
Output 輸出二叉樹的葉子結(jié)點(diǎn)個(gè)數(shù)。
Example Input abc,,de,g,,f,,,
Example Output 3
Hint
Author xam
以下為accepted代碼
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{ char date; struct node *left; struct node *right;}BinTree;char s[104];int flag, y1;BinTree *root;BinTree * creat()//建樹{ BinTree * root; if(s[flag++] == ','){ root = NULL; } else { root = (BinTree *)malloc(sizeof(BinTree)); root->date = s[flag-1]; root->left = creat(); root->right = creat(); } return root;}void leave(BinTree *root)//計(jì)算葉子數(shù)目{ if(root)///判斷root是否為NULL { if(root->left == NULL && root->right == NULL) { y1++; } leave(root->left); leave(root->right); }}int main(){ while(scanf("%s", s) != EOF) { flag = y1 = 0; root = creat();//調(diào)用建樹函數(shù) leave(root);//調(diào)用計(jì)算葉子數(shù)目函數(shù) printf("%d/n", y1); } return 0;}/***************************************************User name: Result: AcceptedTake time: 0msTake Memory: 112KBSubmit time: 2017-02-07 11:46:51****************************************************/以下為runtime error代碼
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{ char date; struct node *left; struct node *right;}BinTree;char s[54];int flag, y1;BinTree *root;BinTree * creat()//建樹{ BinTree * root; if(s[flag++] == ','){ root = NULL; } else { root = (BinTree *)malloc(sizeof(BinTree)); root->date = s[flag-1]; root->left = creat(); root->right = creat(); } return root;}void leave(BinTree *root)//計(jì)算葉子數(shù)目{ if(!root->left && !root->right){ y1++; }}int main(){ while(scanf("%s", s) != EOF) { flag = y1 = 0; root = creat();//調(diào)用建樹函數(shù) leave(root);//調(diào)用計(jì)算葉子數(shù)目函數(shù) printf("%d/n", y1); } return 0;}/***************************************************User name: LEOResult: Runtime ErrorTake time: 0msTake Memory: 0KBSubmit time: 2017-02-07 11:31:15****************************************************/runtime error cause: 1 在計(jì)算葉子數(shù)目函數(shù)中沒有判斷root是否為NULL;
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注