Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
#include <stdio.h>
#include <stdlib.h>
struct Node {
struct Node* lef_child;
struct Node* rig_child;
int data;
};
static struct Node* create_node(const int data) {
struct Node* node = malloc(sizeof(struct Node));
if (node == NULL) {
fprintf(stderr, "ERROR: could not allocate enough memory!\n");
exit(EXIT_FAILURE);
}
node->lef_child = NULL;
node->rig_child = NULL;
node->data = data;
return node;
}
static void free_tree(struct Node* root) {
if (root == NULL) return;
free_tree(root->lef_child);
free_tree(root->rig_child);
free(root);
}
static void pre_order_traversal(const struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
pre_order_traversal(root->lef_child);
pre_order_traversal(root->rig_child);
}
static void in_order_traversal(const struct Node* root) {
if (root == NULL) return;
in_order_traversal(root->lef_child);
printf("%d ", root->data);
in_order_traversal(root->rig_child);
}
static void post_order_traversal(const struct Node* root) {
if (root == NULL) return;
post_order_traversal(root->lef_child);
post_order_traversal(root->rig_child);
printf("%d ", root->data);
}
static void test_tree_1(void) {
/*
* 1
* / \
* / \
* 2 3
* / \ / \
* 4 5 6 7
*/
struct Node* root = create_node(1);
root->lef_child = create_node(2);
root->lef_child->lef_child = create_node(4);
root->lef_child->rig_child = create_node(5);
root->rig_child = create_node(3);
root->rig_child->lef_child = create_node(6);
root->rig_child->rig_child = create_node(7);
puts("Pre-Order-Traversierung:");
pre_order_traversal(root);
puts("");
puts("In-Order-Traversierung:");
in_order_traversal(root);
puts("");
puts("Post-Order-Traversierung:");
post_order_traversal(root);
puts("");
free_tree(root);
}
int main(void) {
test_tree_1();
return EXIT_SUCCESS;
}