I have written a binary tree code for inserting elements into it in non-recursive method. The code is not working as intended. Regardless of how many times I debug the code, nothing seems to be wrong but I am getting wrong results. I am hoping you guys can help. Thanks in advance.
void insert(int element){
if(root == NULL){
struct elemq *node;
node = (struct elemq *)malloc(sizeof(struct elemq));
node->ele = element;
node->left = NULL;
node->right = NULL;
root = node;
cout << root->ele << "\n";
}
else{
struct elemq *ref;
ref = root;
while(ref != NULL){
if(element <= ref->ele){
if(ref->left == NULL){
struct elemq *node;
node = (struct elemq *)malloc(sizeof(struct elemq ));
node->ele = element;
node->left = NULL;
node->right = NULL;
ref->left = node;
break;
}
else{
ref = ref->left;
}
}
else if(element > ref->ele){
if(ref->right == NULL){
struct elemq *node;
node = (struct elemq *)malloc(sizeof(struct elemq ));
node->ele = element;
node->left = NULL;
node->right = NULL;
ref->right = node;
break;
}
else{
ref = ref->right;
}
}
}
}
}
Every time I try to insert an element, each element is being treated as root, not only the first time. So, every time, the condition if(root == NULL) is true. I declared root as global variable and initialized it to NULL in main(). I came to know this by putting cout << in the first if() condition. I modified my previous post to this new question.
cout << root << "\n";all over the place and seen if it transitions back to zero. Then find where it happens...