This commit is contained in:
Oleksandr Vyshniakov 2025-11-20 16:44:12 +01:00
parent 5ebae7a0e1
commit bd5281e52f

View File

@ -24,7 +24,7 @@ static TreeNode* read_tree_node() {
} }
TreeNode *node = calloc(1, sizeof(TreeNode)); TreeNode *node = calloc(1, sizeof(TreeNode));
if (node == NULL) { if (!node) {
exit(1); exit(1);
} }
@ -37,7 +37,7 @@ static TreeNode* read_tree_node() {
} }
node->yes_branch = read_tree_node(); node->yes_branch = read_tree_node();
node->no_branch = read_tree_node(); node->no_branch = read_tree_node();
return node; return node;
} }
@ -54,15 +54,36 @@ static int count_leafs(TreeNode *root) {
return 0; return 0;
} }
int left_count = count_leafs(root->yes_branch); int left = count_leafs(root->yes_branch);
int right_count = count_leafs(root->no_branch); int right = count_leafs(root->no_branch);
int is_leaf = 0; int is_leaf = 0;
if (root->yes_branch == NULL && root->no_branch == NULL) { if (root->yes_branch == NULL && root->no_branch == NULL) {
is_leaf = 1; is_leaf = 1;
} }
return left_count + right_count + is_leaf; return left + right + is_leaf;
}
static int validate_tree(TreeNode *root) {
if (root == NULL) {
return 0;
}
int is_answer = (root->text[0] == '*');
if (is_answer) {
if (root->yes_branch != NULL || root->no_branch != NULL) {
return 0;
}
return 1;
}
if (root->yes_branch == NULL || root->no_branch == NULL) {
return 0;
}
return validate_tree(root->yes_branch) && validate_tree(root->no_branch);
} }
static void skip_empty_line() { static void skip_empty_line() {
@ -90,7 +111,7 @@ static void run_dialog(TreeNode *root) {
return; return;
} }
char c = 0; char c;
int r = scanf(" %c", &c); int r = scanf(" %c", &c);
if (r != 1) { if (r != 1) {
@ -118,14 +139,15 @@ int main() {
printf("Expert z bufetu to vie.\n"); printf("Expert z bufetu to vie.\n");
if (root == NULL) { if (root == NULL || !validate_tree(root)) {
printf("Chybna databaza\n"); printf("Chybna databaza\n");
free_tree(root);
return 0; return 0;
} }
int total_types = count_leafs(root); int total = count_leafs(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", total_types); printf("Pozna %d druhov ovocia a zeleniny.\n", total);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
run_dialog(root); run_dialog(root);