#include #include #include #include struct tree { char value[50]; struct tree* left; struct tree* right; }; struct tree* read_tree(){ char buffer[50]; memset(buffer,0,50); char* r = fgets(buffer,50,stdin); int x = strlen(buffer); buffer[x-1]='\0'; assert(r); if(buffer[0] != '\0'){ struct tree* node = calloc(1,sizeof(struct tree)); memcpy(node->value, buffer,50); if(buffer[0] != '*'){ if(node->left == NULL){ node->left = read_tree(); } if(node->right == NULL){ node->right = read_tree(); } } return node; } } struct tree* search(struct tree* this){ int c = getchar(); if(this == NULL || this->value[0] == '*'){ return this; } if(c == 'a'){ printf("%s\n", this->left->value); return search(this->left); } else if(c == 'n'){ printf("%s\n", this->right->value); return search(this->right); } } 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); } } struct tree* find_minimum(struct tree *root){ if(root == NULL){ return NULL; } else if(root->left != NULL){ return find_minimum(root->left); } return root; } struct tree* destroy_tree(struct tree* root){ if(root == NULL) return; /*if(root->left == NULL && root->right == NULL){ free(root); return NULL; } else if(root->left == NULL || root->right == NULL){ struct tree* temp; if(root->left == NULL){ temp = root->right; }else{ temp = root->left; } free(root); return temp; } else { struct tree* this = find_minimum(root->left); strcpy(root->value, this->value); root->right = destroy_tree(root->right); }*/ root->left = destroy_tree(root->left); root->right = 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(){ struct tree* tree = NULL; tree = read_tree(); int count = count_leaves(tree); //print_tree(tree, 3); printf("Expert z bufetu to vie.\n"); 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); tree = search(tree); destroy_tree(tree); printf("Koniec\n"); return 0; }