数据结构实验之二叉树三:统计叶子数
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,de,g,f, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Sample Input
abc,de,g,f,
Sample Output
3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count;
struct node
{
char data;
struct node*l,*r;
};
int li;
char a[101];
struct node* c( )
{
char b=a[li++];
struct node *root;
if(b==',') root=NULL;
else
{
root=(struct node*)malloc(sizeof(struct node));
root->data=b;
root->l=c();
root->r=c();
}
return root;
}
int leave(struct node*root)
{
if(root)//前序遍历
{
if(root->l==NULL&&root->r==NULL) count++;
leave(root->l);
leave(root->r);
}
return count;
}
int main()
{
while(gets(a))
{
li=0;
struct node*root;
root=c( );
count=0;
printf("%d\n",leave(root));
}
return 0;
}
求二叉树的层次遍历
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Sample Input
2
abc
bac
abdec
dbeac
Sample Output
abc
abcde
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node*l,*r;
};
struct node*c(char x[],char z[],int n)
{
struct node *root;
int i;
if(n<=0) return NULL;
root=(struct node*)malloc(sizeof(struct node));
root->data=x[0];
for(i=0; i<n; i++)
if(z[i]==x[0]) break;
root->l=c(x+1,z,i);
root->r=c(x+i+1,z+i+1,n-i-1);
return root;
}
int level(struct node*root,int i)//i表示第几层
{
if(!root) return 0;
if(i==1)//表明是树根
{
printf("%c",root->data);
return 1;
}
else return level(root->l,i-1)+level(root->r,i-1);
}
int main()
{
int t;
char a[55],b[55];
scanf("%d",&t);
while(t--)
{
int n;
scanf("%s%s",a,b);
n=strlen(a);
struct node*root;
root=c(a,b,n);
int i;
for(i=1; ; i++)
if(level(root,i)==0) break;//表明已遍历完
printf("\n");
}
return 0;
}