Data structure experiment two fork tree three: statistical leaf number
Problem Description
It is known that a binary tree traverses the input character sequence in order, such as ABC, De, G, F,, (where, represents an empty node). Please establish a binary tree and find the number of leaf nodes of the binary tree.
Input
Continuous input of multiple groups of data, each group of data input a string less than 50 characters in length.
Output
Output the number of leaf nodes of binary tree.
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)//Preorder traversal
{
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;
}
Finding the level traversal of binary tree
Problem Description
We know the preorder traversal and the middle order traversal of a binary tree, and find the level traversal of the binary tree.
Input
There are multiple groups of input data. Input T means there are group T test data. Each group of data has two strings less than 50 in length. The first string is the pre order traversal and the second is the mid order traversal.
Output
Each group outputs the hierarchical traversal of this binary tree.
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 represents the layer
{
if(!root) return 0;
if(i==1)//Indicates the root
{
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;//Indicates traversal is complete
printf("\n");
}
return 0;
}
The establishment and traversal of binary tree in data structure experiment