usaa24/cv7/program.c

144 lines
2.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
#include <string.h>
#define SIZE 200
struct tree
{
char value[SIZE];
struct tree *left, *right;
};
struct tree* read_tree()
{
char buffer[SIZE];
memset(buffer,0,SIZE);
char* r = fgets(buffer,SIZE,stdin);
assert(r);
if(buffer[0]=='\n')
return NULL;
struct tree* node = (struct tree*)calloc(1,sizeof(struct tree));
memcpy(node->value,buffer,SIZE);
node->left=NULL;
node->right=NULL;
if(node->value[0]!='*')
{
node->left=read_tree(node->left);
node->right=read_tree(node->right);
}
return node;
}
void print_tree(struct tree* tree,int offset){
for (int i = 0; i < offset; i++){
printf(".");
}
if(tree)
printf("%s",tree->value);
if (tree->left){
print_tree(tree->left,offset +3);
}
if (tree->right){
print_tree(tree->right,offset +3);
}
}
int kkk(struct tree* tree, int x)
{
if (!tree)
{
return x;
}
x += (tree->value[0] == '*');
x = kkk(tree->left, x);
x = kkk(tree->right, x);
return x;
}
void destroy_tree(struct tree* tree){
if(tree==NULL) return;
destroy_tree(tree->left);
destroy_tree(tree->right);
free(tree);
}
int main(void)
{
struct tree *tr=NULL;
tr=read_tree();
printf("Expert z bufetu to vie.\n");
if(tr==NULL)
{
printf("Chybna databaza\n");
return 0;
}
int kk;
char t;
kk=kkk(tr,0);
printf("Pozna %d druhov ovocia a zeleniny.\n", kk);
struct tree *p=tr;
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
do
{
printf("%s",p->value);
if(p->value[0]=='*')
break;
do{
t=fgetc(stdin);
if(t=='a')
{
p=p->left; break;
}
else if(t=='n')
{
p=p->right; break;
}
else if(t==-1)
{
printf("Koniec vstupu\n");
break;
}
else if(t!='\n')
{
printf("Nerozumiem\n");
t=44;
break;
}
}while(1);
}while(t!=44&&t!=-1);
if(t!=44&&t!=-1) printf("Koniec\n");
destroy_tree(tr);
tr=NULL;
return 0;
}