I’m in the middle of building an AVL Tree until this odd thing happened. When i comment this printf() on line 81, my resulting balance factor shows random(?) number when it’s actual BF is 0. But, when i uncomment the printf() line, the resulting BF shows 0. How is this happening?
#include <stdio.h>
#include <stdlib.h>
struct data {
int num;
struct data *left;
struct data *right;
int bf;
};
struct data *root = NULL;
struct data *create_node(int num){
struct data *new_node = (struct data*)malloc(sizeof(struct data));
new_node->num = num;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
int bf_left(struct data *bot, int depth){
if(bot == NULL){
return depth - 1;
}
int temp = bf_left(bot->left, depth + 1);
int temp2 = bf_left(bot->right, depth + 1);
if(temp > temp2){
return temp;
} else if(temp <= temp2){
return temp2;
}
}
int bf_right(struct data *bot, int depth){
if(bot == NULL){
return depth - 1;
}
int temp = bf_right(bot->left, depth + 1);
int temp2 = bf_right(bot->right, depth + 1);
if(temp > temp2){
return temp;
} else if(temp <= temp2){
return temp2;
}
}
int bf_finder(struct data *bot){
int left = bf_left(bot->left, 1);
int right = bf_right(bot->right, 1);
return left - right;
}
struct data *insert(struct data *bot, int num){
if(bot == NULL){
if(root == NULL){
root = create_node(num);
bot = root;
} else{
return create_node(num);
}
} else if(num < bot->num){
bot->left = insert(bot->left, num);
} else if(num > bot->num){
bot->right = insert(bot->right, num);
}
// printf("%dn", bot->num);
bot->bf = bf_finder(bot);
}
void print_all(struct data *bot){
if(bot != NULL){
print_all(bot->left);
printf("%d. bf: %dn", bot->num, bot->bf);
print_all(bot->right);
}
}
int main(){
insert(root, 10);
insert(root, 9);
insert(root, 11);
insert(root, 12);
print_all(root);
return 0;
}
I’m expecting for my code to show an actual BF of 0 if it’s actually 0 with or without this printf() line because i thought there’s no way a single printf() can affect this much but if i’m wrong, i wanna know what is actually happening.