usaa21/cv8/program.c
2021-11-26 03:00:27 +01:00

89 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define SIZE 100
struct node {
// Otázka aleo odpoveď
char data[SIZE];
struct node* parent;
// Odpoveď áno
struct node* left;
// Odpoveď nie
struct node* right;
};
struct node* read_tree(int* count, int* leafs){
char buffer[SIZE];
memset(buffer,0,SIZE);
char* r = fgets(buffer,SIZE,stdin);
assert(r);
struct node* node = calloc(1,sizeof(struct node));
memcpy(node->data,buffer,SIZE);
if(r[0]!='*'){
*count = *count +1;
node->left=read_tree(count, leafs);
node->right=read_tree(count, leafs);
}else {
*leafs = *leafs+1;
}
return node;
}
void print_tree(struct node* tree,int offset){
for (int i = 0; i < offset; i++){
printf(" ");
}
printf("%s",tree->data);
if (tree->left){
print_tree(tree->left,offset +3);
print_tree(tree->right,offset +3);
}
}
void remove_tree(struct node* node){
if ( node != NULL ){
remove_tree(node->left);
remove_tree(node->right);
free(node);
}
}
void ask(struct node* tree){
printf("%s", tree->data);
if(tree->data[0] == '*'){
puts("Koniec");
return;
}
char buff[SIZE];
char* r = fgets(buff, SIZE, stdin);
r = fgets(buff, SIZE, stdin);
if(r[0] == 'a' && tree->left != NULL){
tree = tree->left;
ask(tree);
}else if(r[0] == 'n' && tree->right != NULL) {
tree = tree->right;
ask(tree);
}else{
return;
}
}
int main(){
struct node* tree;
int count = 0;
int leafs = 0;
tree = read_tree(&count, &leafs);
//print_tree(tree, 20);
puts("Expert z bufetu to vie.");
printf("Pozna %d druhov ovocia a zeleniny.\n",leafs);
puts("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.");
ask(tree);
remove_tree(tree);
return 0;
}