usaa25/du6/program.c
2025-11-20 21:09:27 +01:00

90 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 256
typedef struct Node {
char text[MAX];
struct Node* left;
struct Node* right;
} Node;
Node* read_tree() {
char line[MAX];
if (!fgets(line, MAX, stdin)) return NULL;
if (line[0] == '\n') return NULL;
Node* n = malloc(sizeof(Node));
strcpy(n->text, line);
n->left = NULL;
n->right = NULL;
if (line[0] == '*')
return n;
n->left = read_tree();
n->right = read_tree();
return n;
}
int count_leafs(Node* n) {
if (!n) return 0;
if (n->text[0] == '*') return 1;
return count_leafs(n->left) + count_leafs(n->right);
}
void destroy_tree(Node* n) {
if (!n) return;
destroy_tree(n->left);
destroy_tree(n->right);
free(n);
}
void run(Node* n) {
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
while (1) {
printf("%s", n->text);
if (n->text[0] == '*') {
printf("Koniec\n");
return;
}
char c;
if (scanf(" %c", &c) != 1) {
printf("Nespravny vstup.\n");
return;
}
if (c == 'a') n = n->left;
else if (c == 'n') n = n->right;
else {
printf("Nespravny vstup.\n");
return;
}
}
}
int main() {
Node* root = read_tree();
if (!root) {
printf("Chyba: nepodarilo sa nacitat bazu pravidiel.\n");
return 0;
}
int items = count_leafs(root);
printf("Expert z bufetu to vie.\n");
printf("Pozna %d druhov ovocia a zeleniny.\n", items);
run(root);
destroy_tree(root);
return 0;
}