#include #include #include #include struct tree { char value[50]; struct tree* left; struct tree* right; }; struct tree* read_tree(int* counter){ int* c = counter; printf("%d\n", *c); char buffer[50]; memset(buffer,0,50); char* r = fgets(buffer,50,stdin); int x = strlen(buffer); buffer[x-1]='\0'; if(r == NULL){ printf("Chybna databaza\n"); exit(0); } if(buffer[0] != '\0'){ struct tree* node = calloc(1,sizeof(struct tree)); memcpy(node->value, buffer,50); *c += 1; counter = c; if(buffer[0] != '*'){ if(node->left == NULL){ node->left = read_tree(counter); } if(node->right == NULL){ node->right = read_tree(counter); } } if(node->left != NULL && node->right != NULL){ *c -= 2; counter = c; } if(*c == 1){ r = fgets(buffer,50, stdin); int x = strlen(buffer); buffer[x-1]='\0'; if(buffer[0] != '\0'){ printf("Chybna databaza\n"); exit(0); } } return node; } } void search(struct tree* this){ char buffer[5]; memset(buffer,0,5); char* r = fgets(buffer,5,stdin); if(r == NULL){ printf("Koniec vstupu\n"); exit(0); } if(buffer[0] == '\n'){ search(this); } /*if(buffer[0] != 'a' || buffer[0] != 'n' || buffer[0] != '\n'){ printf("Nerozumiem\n"); exit(0); }*/ if(buffer[0] == 'a'){ if(this->left->value[0] == '*'){ printf("%s\n", this->left->value); printf("Koniec\n"); exit(0); } printf("%s\n", this->left->value); search(this->left); } else if(buffer[0] == 'n'){ if(this->right->value[0] == '*'){ printf("%s\n", this->right->value); printf("Koniec\n"); exit(0); } printf("%s\n", this->right->value); search(this->right); } else{ printf("Nerozumiem\n"); exit(0); } } void print_tree(struct tree* tree,int offset){ int i; for (i = 0; i < offset; i++){ printf(" "); } printf("%s",tree->value); if (tree->left){ print_tree(tree->left,offset +3); print_tree(tree->right,offset +3); } } void destroy_tree(struct tree* root){ if(root == NULL) return; destroy_tree(root->left); destroy_tree(root->right); free(root); root = NULL; } int count_leaves(struct tree* node){ int count = 0; if(node->left == NULL && node->right == NULL){ count = 1; } else{ if(node->left != NULL){ count += count_leaves(node->left); } if(node->right != NULL){ count += count_leaves(node->right); } } return count; } int count_all(struct tree* node){ if(node == NULL){ return 0; } int count = 1; if(node->left != NULL){ count += count_all(node->left); } if(node->right != NULL){ count += count_all(node->right); } return count; } int main(){ printf("Expert z bufetu to vie.\n"); struct tree* tree = NULL; int counter = 0; tree = read_tree(&counter); int count = count_leaves(tree); printf("Pozna %d druhov ovocia a zeleniny.\n", count); printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); printf("%s\n", tree->value); search(tree); destroy_tree(tree); return 0; }