This commit is contained in:
Maksym Kovalchuk 2026-04-16 15:42:42 +00:00
parent b2208b5cad
commit 3510447854

View File

@ -14,13 +14,10 @@ typedef struct Tree {
Tree* readTree() { Tree* readTree() {
char line[SIZE]; char line[SIZE];
if (fgets(line, SIZE, stdin) == NULL) return NULL; if (!fgets(line, SIZE, stdin)) return NULL;
line[strcspn(line, "\r\n")] = 0; line[strcspn(line, "\r\n")] = 0;
if (line[0] == '\0') return NULL; Tree *node = malloc(sizeof(Tree));
Tree *node = (Tree*)malloc(sizeof(Tree));
node->yes = NULL; node->yes = NULL;
node->no = NULL; node->no = NULL;
@ -41,38 +38,40 @@ Tree* readTree() {
return node; return node;
} }
int countLeaves(Tree *node) { int count(Tree *n) {
if (!node) return 0; if (!n) return 0;
if (node->isAnswer) return 1; if (n->isAnswer) return 1;
return countLeaves(node->yes) + countLeaves(node->no); return count(n->yes) + count(n->no);
} }
void freeTree(Tree *node) { void freeTree(Tree *n) {
if (!node) return; if (!n) return;
freeTree(node->yes); freeTree(n->yes);
freeTree(node->no); freeTree(n->no);
free(node); free(n);
} }
void start(Tree *node) { void start(Tree *n) {
char input[SIZE]; char in[SIZE];
while (node && !node->isAnswer) { while (n && !n->isAnswer) {
printf("%s\n", node->text); printf("%s\n", n->text);
if (fgets(input, SIZE, stdin) == NULL) return; if (!fgets(in, SIZE, stdin)) return;
int i = 0; int i = 0;
while (input[i] == ' ' || input[i] == '\t') i++; while (in[i] == ' ' || in[i] == '\t' || in[i] == '\r') i++;
if (input[i] == 'a') if (in[i] == 'a')
node = node->yes; n = n->yes;
else if (in[i] == 'n')
n = n->no;
else else
node = node->no; return;
} }
if (node && node->isAnswer) { if (n) {
printf("* %s\n", node->text); printf("*%s\n", n->text);
printf("Koniec\n"); printf("Koniec\n");
} }
} }
@ -87,7 +86,7 @@ int main() {
return 0; return 0;
} }
printf("Pozna %d druhov ovocia a zeleniny.\n", countLeaves(root)); printf("Pozna %d druhov ovocia a zeleniny.\n", count(root));
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
start(root); start(root);