usaa24/cv7/program.c
2024-11-12 18:05:10 +00:00

108 lines
2.5 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 100
struct tree {
char value[SIZE];
struct tree* left;
struct tree* right;
};
// Function to read a single node from input
struct tree* read_tree() {
char buffer[SIZE];
if (fgets(buffer, SIZE, stdin) == NULL || buffer[0] == '\n') {
return NULL; // Return NULL for empty input
}
buffer[strcspn(buffer, "\n")] = 0; // Remove newline character
struct tree* node = calloc(1, sizeof(struct tree));
strncpy(node->value, buffer, SIZE - 1);
return node;
}
// Function to load the tree structure from input
struct tree* load_tree() {
struct tree* node = read_tree();
if (!node) {
return NULL;
}
if (node->value[0] != '*') { // Not an answer, so load children
node->left = load_tree();
node->right = load_tree();
}
return node;
}
// Function to run the tree and interact with the user
void run_tree(struct tree* tree) {
if (!tree) {
return;
}
if (tree->value[0] == '*') {
// If it's an answer
printf("*%s\nKoniec\n", tree->value + 1);
return;
}
printf("%s\n", tree->value);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
char response;
while (1) {
// Wait for user input
if (scanf(" %c", &response) != 1 || (response != 'a' && response != 'n')) {
printf("Nerozumiem\n");
// Re-prompt for input
continue;
}
break; // Valid input received
}
if (response == 'a') {
run_tree(tree->left);
} else {
run_tree(tree->right);
}
}
// Function to free the memory allocated for the tree
void destroy_tree(struct tree* tree) {
if (tree) {
destroy_tree(tree->left);
destroy_tree(tree->right);
free(tree);
}
}
// Function to count the number of unique items (answers) in the tree
void count_items(struct tree* tree, int* count) {
if (tree) {
if (tree->left == NULL && tree->right == NULL) {
(*count)++; // It's a leaf node (an answer)
} else {
count_items(tree->left, count);
count_items(tree->right, count);
}
}
}
int main() {
printf("Expert z bufetu to vie.\n");
struct tree* root = load_tree();
if (!root) {
printf("Chybna databaza\n");
return 0;
}
int count = 0;
count_items(root, &count);
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
run_tree(root);
destroy_tree(root);
return 0;
}