usaa20/cv8/program.c
Maryna Kravtsova 9612fdbc1b buffet
2020-11-22 13:06:22 +01:00

128 lines
2.7 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
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'){
return NULL;
}
struct tree* node = calloc(1,sizeof(struct tree));
/*if(buffer[0] == '\0'){
return node;
}*/
memcpy(node->value, buffer,50);
if(buffer[0] != '*'){
if(node->left == NULL){
node->left = read_tree();
}
if(node->right == NULL){
node->right = read_tree();
}
}
//if(node->left != NULL && node->right != NULL){
return node;
// }
}
struct tree* search(struct tree* this){
/*char question[30] = "Je to ovocie alebo zelenina";
if(strcmp(this->value,question) == 0){
printf("%s\n", this->value);
this = search(this);
}*/
char c = getchar();
/*char buffer[50];
memset(buffer, 0, 50);
int x = strlen(buffer);
buffer[x-1]='\0';
memcpy(buffer, this->value, 50); */
if(this != 0){
if(c == 'a'){
printf("%s\n", this->value);
this = search(this->left);
}
else if(c == 'n'){
printf("%s\n", this->value);
this = search(this->right);
}
}
else {
printf("%s\n", this->value);
printf("Koniec\n");
exit(0);
}
}
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(){
struct tree* tree = NULL;
tree = read_tree();
int count = count_leaves(tree);
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");
tree = search(tree);
return 0;
}