usaa25/du6/program.c
2025-11-21 08:36:28 +01:00

126 lines
2.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 256
typedef struct tree {
char value[SIZE];
struct tree *left;
struct tree *right;
} Tree;
void strip_newline(char *s) {
int len = strlen(s);
if (len > 0 && s[len-1] == '\n') {
s[len-1] = '\0';
}
}
// rekurzivne nacitanie stromu v preorder
Tree* read_tree() {
char buffer[SIZE];
if (!fgets(buffer, SIZE, stdin))
return NULL;
// prazdny riadok -> koniec
if (strcmp(buffer, "\n") == 0)
return NULL;
Tree *node = calloc(1, sizeof(Tree));
strcpy(node->value, buffer);
// odpoved -> list
if (buffer[0] == '*') {
node->left = NULL;
node->right = NULL;
} else {
node->left = read_tree();
node->right = read_tree();
}
return node;
}
void destroy_tree(Tree *tree) {
if (!tree) return;
destroy_tree(tree->left);
destroy_tree(tree->right);
free(tree);
}
int count_leaves(Tree *tree) {
if (!tree) return 0;
if (!tree->left && !tree->right) return 1;
return count_leaves(tree->left) + count_leaves(tree->right);
}
// spustenie znalostneho systemu
int run_system(Tree *node) {
if (node == NULL){
return 1;
}
if (node->value[0] == '*'){
printf("%s\n", node->value);
return 1;
}
char c[10];
printf("%s\n", node->value);
if (fgets(c, sizeof(c), stdin) == NULL) {
printf("Koniec vstupu\n");
return 0;
}
strip_newline(c);
if (!node->left && !node->right) {
printf("Koniec vstupu\n");
return 0;
}
if (strcmp(c,"a") == 0) {
if (node->left != NULL){
return run_system(node->left);
}
} else if (strcmp(c, "n") == 0) {
if (node->right != NULL){
return run_system(node->right);
}
} else {
printf("Nerozumiem\n");
return 0;
}
return 1;
}
int main() {
Tree *root = read_tree();
printf("Expert z bufetu to vie.\n");
if (root == NULL){
printf("Chybna databaza\n");
return 0;
}
/* // skontrolovat prazdny riadok
char buffer[SIZE];
if (!fgets(buffer, SIZE, stdin) || strlen(buffer) > 1) {
printf("Chybna databaza\n");
destroy_tree(root);
return 0;
}*/
int leaves = count_leaves(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", leaves);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
int continueworking = run_system(root);
if (continueworking){
printf("Koniec\n");
}
destroy_tree(root);
return 0;
}