Initializacia

This commit is contained in:
Kozar 2024-11-10 15:36:06 +00:00
parent 7a96dc2c17
commit ea6d529fad

View File

@ -1,23 +1,26 @@
#include<stdio.h> #include <stdio.h>
#include<string.h> #include <string.h>
#include<assert.h> #include <assert.h>
#include<stdlib.h> #include <stdlib.h>
#define SIZE 100 #define SIZE 100
struct tree{ struct tree {
char value[SIZE]; char value[SIZE];
struct tree* left; struct tree* left;
struct tree* right; struct tree* right;
}; };
struct tree* read_tree(){ struct tree* read_tree() {
char buffer[SIZE]; char buffer[SIZE];
memset(buffer,0,SIZE); memset(buffer, 0, SIZE);
char* r = fgets(buffer,SIZE,stdin); char* r = fgets(buffer, SIZE, stdin);
assert(r); if (!r || buffer[0] == '\n') {
struct tree* node = calloc(1,sizeof(struct tree)); return NULL;
memcpy(node->value,buffer,SIZE); }
buffer[strcspn(buffer, "\n")] = 0;
struct tree* node = calloc(1, sizeof(struct tree));
strncpy(node->value, buffer, SIZE - 1);
return node; return node;
} }
@ -33,31 +36,45 @@ struct tree* load_tree() {
return node; return node;
} }
void print_tree(struct tree* tree, int offset){ void print_tree(struct tree* tree, int offset) {
for (int i = 0; i < offset; i++){ if (!tree) {
printf(" "); return;
} }
printf("%s", tree->value);
if (tree->left){ if (tree->value[0] == '*') {
printf("Expert z bufetu to vie.\n%s\nKoniec\n", tree->value + 1);
return;
}
printf("%s\n", tree->value);
char response;
if (scanf(" %c", &response) != 1 || (response != 'a' && response != 'n')) {
printf("Nespravny vstup. Koniec.\n");
return;
}
if (response == 'a') {
print_tree(tree->left, offset + 3); print_tree(tree->left, offset + 3);
} else {
print_tree(tree->right, offset + 3); print_tree(tree->right, offset + 3);
} }
} }
void destroy_tree(struct tree* tree){ void destroy_tree(struct tree* tree) {
if(tree->left != NULL){ if (tree->left != NULL) {
destroy_tree(tree->left); destroy_tree(tree->left);
} }
if(tree->right != NULL){ if (tree->right != NULL) {
destroy_tree(tree->right); destroy_tree(tree->right);
} }
free(tree); free(tree);
} }
void count_items(struct tree* tree, int* count){ void count_items(struct tree* tree, int* count) {
if(tree->left == NULL && tree->right == NULL){ if (tree->left == NULL && tree->right == NULL) {
(*count)++; (*count)++;
}else{ } else {
count_items(tree->left, count); count_items(tree->left, count);
count_items(tree->right, count); count_items(tree->right, count);
} }
@ -75,7 +92,7 @@ int main() {
printf("Pozna %d druhov ovocia a zeleniny.\n", count); printf("Pozna %d druhov ovocia a zeleniny.\n", count);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
print_tree(root); print_tree(root, 0);
destroy_tree(root); destroy_tree(root);
return 0; return 0;