74 lines
1.5 KiB
C
74 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <assert.h>
|
|
|
|
#define SIZE 256
|
|
|
|
// Struktúra uzla
|
|
typedef struct tree {
|
|
char value[SIZE];
|
|
struct tree* left;
|
|
struct tree* right;
|
|
} Tree;
|
|
|
|
// Funkcia na vytvorenie nového uzla
|
|
Tree* create_node(const char* value) {
|
|
Tree* node = malloc(sizeof(Tree));
|
|
if (node) {
|
|
strncpy(node->value, value, SIZE);
|
|
node->left = NULL;
|
|
node->right = NULL;
|
|
}
|
|
return node;
|
|
}
|
|
|
|
// Funkcia na načítanie stromu
|
|
Tree* read_tree() {
|
|
char buffer[SIZE];
|
|
memset(buffer, 0, SIZE);
|
|
|
|
// Čítanie riadku
|
|
if (!fgets(buffer, SIZE, stdin)) {
|
|
return NULL;
|
|
}
|
|
|
|
// Odstránenie znaku nového riadku
|
|
buffer[strcspn(buffer, "\n")] = 0;
|
|
|
|
if (buffer[0] == '\0') {
|
|
return NULL; // Prázdny riadok znamená koniec
|
|
}
|
|
|
|
Tree* node = create_node(buffer);
|
|
|
|
// Ak ide o odpoveď, nečítame podstromy
|
|
if (buffer[0] == '*') {
|
|
return node;
|
|
}
|
|
|
|
// Čítanie podstromov (ľavý a pravý uzol)
|
|
node->left = read_tree();
|
|
node->right = read_tree();
|
|
return node;
|
|
}
|
|
|
|
// Funkcia na zničenie stromu
|
|
void destroy_tree(Tree* tree) {
|
|
if (tree) {
|
|
destroy_tree(tree->left);
|
|
destroy_tree(tree->right);
|
|
free(tree);
|
|
}
|
|
}
|
|
|
|
// Funkcia na preorder výpis stromu
|
|
void print_tree(Tree* tree, int offset) {
|
|
if (tree == NULL) return;
|
|
for (int i = 0; i < offset; i++) {
|
|
printf(" ");
|
|
}
|
|
printf("%s\n", tree->value);
|
|
print_tree(tree->left, offset + 3);
|
|
print_tree(tree->right, offset + 3);
|
|
} |