usaa24/cv7/program.c

66 lines
1.3 KiB
C
Raw Normal View History

2024-11-09 21:40:16 +00:00
#include<stdio.h>
#include<string.h>
#include<assert.h>
2024-11-10 14:42:10 +00:00
#include<stdlib.h>
2024-11-09 21:40:16 +00:00
#define SIZE 100
struct tree{
char value[SIZE];
struct tree* left;
struct tree* right;
};
struct tree* read_tree(){
char buffer[SIZE];
memset(buffer,0,SIZE);
char* r = fgets(buffer,SIZE,stdin);
assert(r);
struct tree* node = calloc(1,sizeof(struct tree));
memcpy(node->value,buffer,SIZE);
return node;
}
2024-11-09 21:50:22 +00:00
struct tree* load_tree() {
struct tree* node = read_tree();
if (!node) {
return NULL;
}
if (node->value[0] != '*') {
node->left = load_tree();
node->right = load_tree();
2024-11-09 21:40:16 +00:00
}
2024-11-09 21:50:22 +00:00
return node;
2024-11-09 21:40:16 +00:00
}
2024-11-10 14:51:44 +00:00
void print_tree(struct tree* tree, int offset){
2024-11-09 21:40:16 +00:00
for (int i = 0; i < offset; i++){
printf(" ");
}
2024-11-10 14:51:44 +00:00
printf("%s", tree->value);
2024-11-09 21:40:16 +00:00
if (tree->left){
2024-11-10 14:51:44 +00:00
print_tree(tree->left, offset + 3);
print_tree(tree->right, offset + 3);
2024-11-09 21:40:16 +00:00
}
}
void destroy_tree(struct tree* tree){
if(tree->left != NULL){
destroy_tree(tree->left);
}
if(tree->right != NULL){
destroy_tree(tree->right);
}
free(tree);
}
void count_items(struct tree* tree, int* count){
if(tree->left == NULL && tree->right == NULL){
2024-11-10 14:49:17 +00:00
(*count)++;
2024-11-09 21:40:16 +00:00
}else{
count_items(tree->left, count);
count_items(tree->right, count);
}
}