This commit is contained in:
Denis Landa 2025-11-20 21:06:31 +01:00
parent 0bcc777c74
commit 0f5f86fa92

View File

@ -2,93 +2,87 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define VELKOST 256 #define MAX 256
struct Uzol{ typedef struct Node {
char text[VELKOST]; char text[MAX];
struct Uzol* ano; struct Node* left;
struct Uzol* nie; struct Node* right;
}; } Node;
struct Uzol* nacitaj_uzol(){ Node* read_tree() {
char riadok[VELKOST]; char line[MAX];
if (!fgets(line, MAX, stdin)) return NULL;
if (line[0] == '\n') return NULL;
if(!fgets(riadok, VELKOST, stdin)) Node* n = malloc(sizeof(Node));
return NULL; strcpy(n->text, line);
n->left = NULL;
n->right = NULL;
if(riadok[0] == '\n') if (line[0] == '*') {
return NULL; return n;
struct Uzol* u = malloc(sizeof(struct Uzol));
strcpy(u->text, riadok);
u->ano = NULL;
u->nie = NULL;
if(riadok[0] == '*'){
return u;
} }
u->ano = nacitaj_uzol(); n->left = read_tree();
u->nie = nacitaj_uzol(); n->right = read_tree();
return u; return n;
} }
void zrus_strom(struct Uzol* u){ int count_leafs(Node* n) {
if(!u) return; if (!n) return 0;
zrus_strom(u->ano); if (n->text[0] == '*') return 1;
zrus_strom(u->nie); return count_leafs(n->left) + count_leafs(n->right);
free(u);
} }
int pocet_tovarov(struct Uzol* u){ void destroy_tree(Node* n) {
if(!u) return 0; if (!n) return;
if(u->text[0] == '*') return 1; destroy_tree(n->left);
return pocet_tovarov(u->ano) + pocet_tovarov(u->nie); destroy_tree(n->right);
free(n);
} }
void spusti_system(struct Uzol* u){ void run(Node* n) {
if(u->text[0] == '*'){ printf("Odpovedajte 'a' alebo 'n'\n");
printf("%s", u->text);
while (1) {
printf("%s", n->text);
if (n->text[0] == '*') {
printf("Koniec\n"); printf("Koniec\n");
return; return;
} }
printf("Nerozumiem\n");
printf("%s", u->text);
char c; char c;
if(scanf(" %c", &c) != 1){ if (scanf(" %c", &c) != 1) {
printf("Chyba vstupu.\n"); printf("Nespravny vstup.\n");
return; return;
} }
if(c == 'a'){ if (c == 'a') n = n->left;
spusti_system(u->ano); else if (c == 'n') n = n->right;
else {
printf("Nespravny vstup.\n");
return;
} }
else if(c == 'n'){
spusti_system(u->nie);
}
else{
printf("Nerozumiem\n");
} }
} }
int main(){ int main() {
struct Uzol* koren = nacitaj_uzol(); Node* root = read_tree();
if (!root) {
if(!koren){
printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n"); printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n");
return 0; return 0;
} }
int pocet = pocet_tovarov(koren); int items = count_leafs(root);
printf("Expert z bufetu to vie.\n"); printf("MUDrC to vie.\n");
printf("Pozna %d druhov ovocia a zeleniny.\n", pocet); printf("Pozna %d druhov ovocia a zeleniny.\n", items);
spusti_system(koren); run(root);
zrus_strom(koren);
destroy_tree(root);
return 0; return 0;
} }