1. 程式人生 > >資料結構實驗之二叉樹三:統計葉子數 SDUT 3342

資料結構實驗之二叉樹三:統計葉子數 SDUT 3342

#include <stdio.h>
#include <string.h>

struct node
{
    char data;
    struct node *l,*r;
};
struct node *root;
char st[51];
int i;
int count;
struct node *creat()
{
    struct node *root;
    if(st[i++] == ',')
        root = NULL;
    else
    {
        root = (struct node *)malloc(sizeof(struct node));
        root->data = st[i-1];
        root->l = creat();
        root->r = creat();
    }
    return root;
}
int search(struct node *root)
{
    if(root)
    {
        if((root->l==NULL) && (root->r== NULL))
        {
            count++;
        }
        search(root->l);
        search(root->r);
    }
    return 0;
}
int main()
{
    while(~scanf("%s",st))
    {
        i = 0;
        count = 0;
        root = creat();
        search(root);
        printf("%d\n",count);
    }
    return 0;
}