資料結構實驗之二叉樹三:統計葉子數
阿新 • • 發佈:2018-12-19
Problem Description
已知二叉樹的一個按先序遍歷輸入的字元序列,如abc,de,g,f, (其中,表示空結點)。請建立二叉樹並求二叉樹的葉子結點個數。 Input
連續輸入多組資料,每組資料輸入一個長度小於50個字元的字串。 Output
輸出二叉樹的葉子結點個數。 Sample Input
abc,de,g,f, Sample Output
3 就是把所有節點走一遍找根節點不為空,但是左右子樹根節點為空的根的個數。
#include <stdlib.h> #include <stdio.h> char a[100]; int n; int count; struct node { char data; struct node *left; struct node *right; }; struct node *create() { struct node *root; if(a[n]==',') { n++; root=NULL; } else { root=(struct node *)malloc(sizeof(struct node)); root->data=a[n]; n++; root->left=create(); root->right=create(); } return root; } void find(struct node *root) { if(root) { if(!(root->left)&&!(root->right)) { count++; } find(root->left); find(root->right); } } int main() { while(~scanf("%s",a)) { count=0; n=0; struct node *root=create(); find(root); printf("%d\n",count); } return 0; }