From d819a083dfd552fca46285ff30731f856d5c36fe Mon Sep 17 00:00:00 2001 From: Ivan Leichenko Date: Fri, 15 Nov 2024 05:36:39 +0100 Subject: [PATCH] add cv7 --- cv7/program.c | 125 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 cv7/program.c diff --git a/cv7/program.c b/cv7/program.c new file mode 100644 index 0000000..0692f46 --- /dev/null +++ b/cv7/program.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include + +#define SIZE 256 + +struct tree +{ + char value[SIZE]; + struct tree *left; + struct tree *right; +}; + +struct tree* read_tree() +{ + char buffer[SIZE]; + if (!fgets(buffer, SIZE, stdin) || buffer[0] == '\n') + { + return NULL; + } + + buffer[strcspn(buffer, "\n")] = 0; + + struct tree *node = (struct tree*)malloc(sizeof(struct tree)); + assert(node != NULL); + strcpy(node->value, buffer); + + if (buffer[0] != '*') + { + node->left = read_tree(); + node->right = read_tree(); + } + else + { + node->left = NULL; + node->right = NULL; + } + + return node; +}; + +void free_tree(struct tree *tree) +{ + if (tree == NULL) + { + return; + } + free_tree(tree->left); + free_tree(tree->right); + free(tree); +} + +int count_leaf_nodes(struct tree *node) +{ + if (node == NULL) + { + return 0; + } + if (node->left == NULL && node->right == NULL) + { + return 1; + } + return count_leaf_nodes(node->left) + count_leaf_nodes(node->right); +} + +int count_non_leaf_nodes(struct tree *node) +{ + if (node == NULL || (node->left == NULL && node->right == NULL)) + { + return 0; + } + return 1 + count_non_leaf_nodes(node->left) + count_non_leaf_nodes(node->right); +} + +void interact(struct tree *node) +{ + if (node == NULL) + { + return; + } + + printf("%s (a/n) ?\n", node->value); + + if (node->left == NULL && node->right == NULL) + { + printf("Koniec\n"); + return; + } + + char answer; + while (scanf(" %c", &answer) == 1) + { + if (answer == 'a') + { + interact(node->left); + return; + } + else if (answer == 'n') + { + interact(node->right); + return; + } + else + { + printf("Odpovedajte 'a' alebo 'n'\n"); + } + } +} + +int main() +{ + struct tree *root = read_tree(); + + if (root == NULL) + { + printf("Chyba pri nacitani databazy pravidiel.\n"); + return 1; + } + + interact(root); + free_tree(root); + + return 0; +} \ No newline at end of file