資料結構實驗之二叉樹三:統計葉子數
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知二叉樹的一個按先序周遊輸入的字元序列,如abc,de,g,f, (其中,表示空結點)。請建立二叉樹并求二叉樹的葉子結點個數。
Input
連續輸入多組資料,每組資料輸入一個長度小于50個字元的字元串。
Output
輸出二叉樹的葉子結點個數。
Sample Input
abc,de,g,f,
Sample Output
3
Hint
Source
xam
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *r,*l;
};
char a[55];
int i;
int len;
struct node *creat()//遞歸建立二叉樹//
{
char c;
struct node *root;
c=a[i++];
if(c==',')
return NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=c;
root->l=creat();
root->r=creat();
}
return root;
};
void shu(struct node *root)
{
if(root)
{
if(root->l)
shu(root->l);
if(root->r)
shu(root->r);//遞歸左右子樹//
if(root->l==NULL&&root->r==NULL)
len++;//找到一個左右子樹為空的節點就加一//
}
return;//函數遞歸終止條件//
}
int main()
{
struct node *root;
while(scanf("%s",a)!=EOF)
{
i=0;
len=0;
root=(struct node *)malloc(sizeof(struct node));
root=creat();
shu(root);
printf("%d\n",len);
}
return 0;
}