113 lines
2.3 KiB
C
113 lines
2.3 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;
|
|
};
|
|
|
|
int error_flag = 0;
|
|
|
|
struct tree* read_tree() {
|
|
char buffer[SIZE];
|
|
memset(buffer, 0, SIZE);
|
|
char* r = fgets(buffer, SIZE, stdin);
|
|
if (!r || buffer[0] == '\n') {
|
|
return NULL;
|
|
}
|
|
buffer[strcspn(buffer, "\n")] = 0;
|
|
struct tree* node = calloc(1, sizeof(struct tree));
|
|
if (buffer[0] == '*') {
|
|
if (strlen(buffer) <= 1) {
|
|
error_flag = 1;
|
|
}
|
|
}
|
|
strncpy(node->value, buffer, SIZE - 1);
|
|
return node;
|
|
}
|
|
|
|
struct tree* load_tree() {
|
|
struct tree* node = read_tree();
|
|
if (!node) {
|
|
return NULL;
|
|
}
|
|
if (error_flag || node->value[0] != '*') {
|
|
node->left = load_tree();
|
|
node->right = load_tree();
|
|
}
|
|
return node;
|
|
}
|
|
|
|
void run_tree(struct tree* tree) {
|
|
if (!tree) {
|
|
return;
|
|
}
|
|
|
|
if (tree->value[0] == '*') {
|
|
printf("*%s\nKoniec\n", tree->value + 1);
|
|
return;
|
|
}
|
|
|
|
printf("%s\n", tree->value);
|
|
|
|
char response;
|
|
if (scanf(" %c", &response) != 1) {
|
|
printf("Koniec vstupu\n");
|
|
return;
|
|
} else if (response != 'a' && response != 'n') {
|
|
printf("Nerozumiem\n");
|
|
return;
|
|
}
|
|
|
|
if (response == 'a') {
|
|
run_tree(tree->left);
|
|
} else {
|
|
run_tree(tree->right);
|
|
}
|
|
}
|
|
|
|
void destroy_tree(struct tree* tree) {
|
|
if (!tree) {
|
|
return;
|
|
}
|
|
destroy_tree(tree->left);
|
|
destroy_tree(tree->right);
|
|
free(tree);
|
|
}
|
|
|
|
void count_items(struct tree* tree, int* count) {
|
|
if (!tree) {
|
|
return;
|
|
}
|
|
if (tree->left == NULL && tree->right == NULL) {
|
|
(*count)++;
|
|
} else {
|
|
count_items(tree->left, count);
|
|
count_items(tree->right, count);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
struct tree* root = load_tree();
|
|
printf("Expert z bufetu to vie.\n");
|
|
if (!root || error_flag) {
|
|
printf("Chybna databaza\n");
|
|
destroy_tree(root);
|
|
return 0;
|
|
}
|
|
|
|
int count = 0;
|
|
count_items(root, &count);
|
|
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
|
|
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
|
|
|
|
run_tree(root);
|
|
|
|
destroy_tree(root);
|
|
return 0;
|
|
}
|