usaa20/cv8/program.c
Maryna Kravtsova 5c6d8f47dc buffet
2020-11-21 18:36:39 +01:00

138 lines
2.9 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
struct tree {
char value[30];
struct tree* left;
struct tree* right;
};
struct tree* read_tree(){
char buffer[30];
memset(buffer,0,30);
char* r = fgets(buffer,30,stdin);
int x = strlen(buffer);
buffer[x-1]='\0';
assert(r);
struct tree* node = calloc(1,sizeof(struct tree));
if(buffer[0] == '\0'){
return node;
}
memcpy(node->value, buffer,30);
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;
// }
}
void print_tree(struct tree* node, int offset){
int i;
for (i = 0; i < offset; i++){
printf(" ");
}
printf("%s",node->value);
if (node->left){
print_tree(node->left,offset + 3);
print_tree(node->right,offset + 3);
}
}
struct tree* search(struct tree* this){
char buffer[5];
memset(buffer,0,5);
char* r = fgets(buffer,5,stdin);
int x = strlen(buffer);
buffer[x-1]='\0';
if(buffer[0] != 'a' && buffer[0] != 'n'){
printf("Chyba\n");
exit(0);
}
if(this != NULL){
if(buffer[0] == 'a'){
printf("%s\n", this->value);
this->left = search(this);
}
else if(buffer[0] == 'n'){
printf("%s\n", this->value);
this->right = search(this);
}
}
else{
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");
printf("%s\n", tree->value);
tree = search(tree);
//print_tree(tree, 3);
//display(tree);
destroy_tree(tree);
return 0;
}