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;
}
if/elseblocks are not grouped the way you intended.inicioas the global variable that holds the pointer to the start of the list.