usaa25/du6/program.c
2025-11-09 18:55:41 +01:00

132 lines
2.9 KiB
C

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 100
struct tree{
char value[SIZE];
struct tree* left;
struct tree* right;
};
void destroy_tree(struct tree* tree){
if(tree->left){
destroy_tree(tree->left);
}
if(tree->right){
destroy_tree(tree->right);
}
free(tree);
}
struct tree* read_tree(){
char buffer[SIZE];
memset(buffer,0,SIZE);
char* r = fgets(buffer,SIZE,stdin);
if(!r) {
return NULL;
}
r[strcspn(r, "\n")] = '\0';
assert(r);
struct tree* node = calloc(1,sizeof(struct tree));
memcpy(node->value,buffer,SIZE);
if(buffer[0] == '*'){
node->left = NULL;
node->right = NULL;
return node;
}
node->left = read_tree();
node->right = read_tree();
// Ak je nacitany riadok listovy uzol ,tak netreba robit nic
// inak rekurzivne nacitanie laveho syna
// a rekurzivne nacitanie praveho syna
return node;
}
void print_tree(struct tree* tree,int offset){
for (int i = 0; i < offset; i++){
printf(" ");
}
printf("%s",tree->value);
if (tree->left){
print_tree(tree->left,offset +3);
print_tree(tree->right,offset +3);
}
}
int count_leaves(struct tree* tree){
int count = 0;
if(tree == NULL){
return count;
}
if(tree->left == NULL && tree->right == NULL && tree){
return count +1;
}
else{
return count + count_leaves(tree->left) + count_leaves(tree->right);
}
}
int main(void){
bool whitespace = false;
struct tree* tree = read_tree();
char line[SIZE];
while( fgets(line, sizeof(line), stdin)){
if(strcmp(line, "\n") == 0){
whitespace = true;
break;
}
}
int numOfLeaves = count_leaves(tree);
char answer[SIZE];
printf("Expert z bufetu to vie.\n");
if(!tree || !whitespace){
printf("Chybna databaza\n");
return 0;
}
printf("Pozna %d druhov ovocia a zeleniny.\n", numOfLeaves);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.");
while(tree){
printf("\n%s", tree->value);
if( fgets(answer, sizeof(answer), stdin)){
printf("\nKoniec vstupu\n");
return 0;
}
answer[strcspn(answer, "\n")] = '\0';
if(strcmp(answer, "n") == 0){
tree = tree->right;
if(tree->value[0] == '*'){
printf("\n%s\n", tree->value);
printf("Koniec\n");
return 0;
}
}
else if(strcmp(answer, "a") == 0){
tree = tree->left;
if(tree->value[0] == '*'){
printf("\n%s\n", tree->value);
printf("Koniec\n");
return 0;
}
}
else{
printf("\nNerozumiem\n");
return 0;
}
}
destroy_tree(tree);
return 0;}