Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Example Input
abc,,de,g,,f,,,
Example Output
3
01 | #include<stdio.h> |
02 | #include<stdlib.h> |
03 | #include<string.h> |
04 | char a[55]; |
05 | int flag; |
06 | struct node |
07 | { |
08 | char date; |
09 | struct node *l, *r; |
10 | }; |
11 | struct node *creat() |
12 | { |
13 | struct node *root; |
14 | if (a[++flag] == ',' ) |
15 | { |
16 | root = NULL; |
17 | } |
18 | else |
19 | { |
20 | root = ( struct node *) malloc ( sizeof ( struct node)); |
21 | root->date = a[flag]; |
22 | root->l = creat(); |
23 | root->r = creat(); |
24 | } |
25 | return root; |
26 | } |
27 | int leave( struct node *root) |
28 | { |
29 | if (root == NULL) return 0; |
30 | if (root->l == NULL && root->r == NULL) return 1; |
31 | else |
32 | return leave(root->l) + leave(root->r); |
33 | } |
34 | int main() |
35 | { |
36 | int d; |
37 | while ( scanf ( "%s" , a) != EOF) |
38 | { |
39 | flag = -1; |
40 | struct node *root; |
41 | root = creat(); |
42 | d = leave(root); |
43 | printf ( "%d\n" , d); |
44 | } |
45 | return 0; |
46 | } |
47 |