My Binary Tree code in C isn't running at all and I'm not sure exactly why. Is there anything blatantly wrong in the function? It runs with just one insert use, but any more and it stops working. It's just supposed to be a simple function that inserts ints at their right place along the tree.
#include <stdio.h>
#include <stdlib.h>
typedef struct trees Tree;
struct trees {
int data;
Tree *left;
Tree *right;
};
Tree *inicio=NULL;
void insert(int n){
Tree *novo = (Tree*)malloc(sizeof(Tree));
Tree *aux;
Tree *pai;
novo->data=n;
novo->left=NULL;
novo->right=NULL;
if(inicio==NULL){
inicio = novo;
return;
} else {
aux = inicio;
pai = NULL;
while(1){
pai = aux;
if(n>pai->data){
aux=aux->right;
if(aux==NULL){
pai->right=novo;
return;
} else {
aux=aux->left;
if(aux==NULL){
pai->left=novo;
return;
}
}
}
}
}
}
int main() {
insert(9);
insert(8);
printf("[%p] -> (%p, %d, %p)\n",inicio,inicio->left,inicio->data,inicio->right);
return 0;
}
to illustrate @kaylum point, here is the relevant part reformatted
while(1){
pai = aux;
if(n>pai->data){
aux=aux->right;
if(aux==NULL){
pai->right=novo;
return;
} // end if(aux==NULL)
else
{ // else => aux != NULL
aux=aux->left;
if(aux==NULL){
pai->left=novo;
return;
} // end if(aux==NULL)
} // end else
} // end if(n>pai->data)
} // end while
Please Note that else
after return
are pointless noise
while(1){
pai = aux;
if(n > pai->data){
aux = aux->right;
if(aux == NULL){
pai->right = novo;
return;
}
continue; // skip to next loop
}
// implying (n <= pai->data)
aux = aux->left;
if(aux == NULL){
pai->left = novo;
return;
}
}
"Better" implementation would probably use pointer to pointer and reduce redundant code.
void insert(int n)
{
Tree **pp = &inicio;
while (*pp)
{
if ((*pp)->data < n)
pp = &(*pp)->right;
else
pp = &(*pp)->left;
}
*pp = malloc(sizeof **pp);
if (*pp)
{
(*pp)->data = n;
(*pp)->left = (*pp)->right = NULL;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.