The function gets a root of a Binary Tree of ints, and a function f. it applies f to the data of each node in the tree.
BTnode_t* create_node(int val) {
BTnode_t* newNode = (BTnode_t*) malloc(sizeof(BTnode_t));
newNode->value = val;
newNode->left = NULL;
newNode->right = NULL;
newNode->parent = NULL;
returnnewNode;
}
void set_left_child(BTnode_t* parent, BTnode_t* left_child) {
if (parent)
parent->left = left_child;
if (left_child)
left_child->parent = parent;
}
void set_right_child(BTnode_t* parent, BTnode_t* right_child) {
if (parent)
parent->right = right_child;
if (right_child)
right_child->parent = parent;
}
void print_pre_order(BTnode_t* root) {
if (root == NULL)
return;
printf("%d ", root->value);
print_pre_order(root->left);
print_pre_order(root->right);
}
void print_in_order(BTnode_t* root) {
if (root == NULL)
return;
print_in_order(root->left);
printf("%d ", root->value);
print_in_order(root->right);
}
void print_post_order(BTnode_t* root) {
if (root == NULL)
return;
print_post_order(root->left);
print_post_order(root->right);
printf("%d ", root->value);
}
Test for the function:
int square(int x) { return x*x;}
bool test_q3map() {
/***
// creates the following tree
// 1
// / \
// 2 3
****/
BTnode_t* one = create_node(1);
BTnode_t* two = create_node(2);
BTnode_t* three = create_node(3);
set_left_child(one, two);
set_right_child(one, three);
map(one, square);
if (one->value == 1 && two->value == 4 && three->value == 9) {
printf("Q3-map ok\n");
returntrue;
}
else {
printf("Q3-map ERROR\n");
returnfalse;
}
}