usaa20/cv8/program.c

125 lines
2.6 KiB
C
Raw Normal View History

2020-11-21 15:26:27 +00:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
struct tree {
char value[20];
struct tree* left;
struct tree* right;
};
/*struct tree* create_node(char* string){
struct tree* node = calloc(1, sizeof(struct tree));
node->left = NULL;
node->right = NULL;
strcpy(node->value, string);
return node;
}*/
struct tree* read_tree(){
char buffer[20];
memset(buffer,0,20);
char* r = fgets(buffer,20,stdin);
int x = strlen(buffer);
buffer[x-1]='\0';
2020-11-21 15:34:20 +00:00
2020-11-21 15:26:27 +00:00
assert(r);
struct tree* node = calloc(1,sizeof(struct tree));
2020-11-21 15:34:20 +00:00
if(buffer[0] == '\0'){
return node;
}
2020-11-21 15:26:27 +00:00
memcpy(node->value, buffer, 20);
/*if(node == NULL){
return create_node();
}*/
if(buffer[0] != '*'){
2020-11-21 16:00:44 +00:00
if(node->left == NULL){
2020-11-21 15:59:00 +00:00
node->left = read_tree();
2020-11-21 16:00:44 +00:00
}
if(node->right == NULL){
2020-11-21 15:59:00 +00:00
node->right = read_tree();
2020-11-21 16:00:44 +00:00
}
2020-11-21 15:26:27 +00:00
}
/*else if(string[0] == '*'){
if(node->left == NULL){
strcpy(node->value, string);
}
else if(node->right == NULL){
strcpy(node->value, string);
}
}*/
2020-11-21 16:00:44 +00:00
//if(node->left != NULL && node->right != NULL){
2020-11-21 15:26:27 +00:00
return node;
2020-11-21 16:00:44 +00:00
//}
2020-11-21 15:26:27 +00:00
}
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 answer){
if(this != NULL){
if(answer == 'a'){
2020-11-21 15:59:00 +00:00
printf("%s\n", this->value);
2020-11-21 15:26:27 +00:00
this->left = search(this, answer);
}
else if(answer == 'n'){
2020-11-21 15:59:00 +00:00
printf("%s\n", this->value);
2020-11-21 15:26:27 +00:00
this->right = search(this, answer);
2020-11-21 15:59:00 +00:00
}
2020-11-21 15:26:27 +00:00
}
else{
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_l(struct tree* node){
if(node == NULL){
return 0;
}
if(node->left == NULL && node->right == NULL){
return 1;
}
else{
2020-11-21 15:59:00 +00:00
return count_l(node->left) + count_l(node->right);
2020-11-21 15:26:27 +00:00
}
}
int main(){
struct tree* tree = NULL;
tree = read_tree();
2020-11-21 15:32:04 +00:00
int count = count_l(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");
2020-11-21 16:04:17 +00:00
2020-11-21 15:26:27 +00:00
//print_tree(tree, 3);
//display(tree);
destroy_tree(tree);
return 0;
}