Bug in AVL tree implementation

Asked

Viewed 41 times

0

I’m trying to implement an AVL tree, but when I call the Inserts function in the main and step some value(int) happens something strange. The first time the if (of the Inserts function) is satisfied, but the second time the function is called the if should not be satisfied, but remains so. NOTE: The first time if is satisfied indicates that the tree is empty. The insert function is not the same as the Insert, but it is not the cause of the problem because it is not even executed.

void Insere(Tree T,int x){
No F;
F = T->no;
if(F == NULL){
    F = (No) malloc(sizeof(struct no));
    F->left = NULL;
    F->right = NULL;
    F->balanceFactor = 0;
    printf("Primeiro numero inserido\n");
}else 
    inserir(F, x);
}

Main:

int main(){
Tree T;
T = inicializar();
Insere(T, 10);
Insere(T, 11);
Insere(T, 9);


return 0;
}

where:

typedef struct arvore* Tree;
typedef struct no* No;

Tree inicializar(){
Tree T;
T = (Tree) malloc(sizeof(struct arvore));
T->no = NULL;

return T;
}

If anyone can help me <3.

  • Note that in the definition of your function Inserts the first parameter is of the Tree type but when recursion you invoke the function with the first parameter being of the type No.

  • This function that is called in Else is another function that receives other types of parameters. the problem is happening in if.

  • A hint: name your variables correctly. What is T? what is no? What is f? You may even know why you’re writing the code now. But if you stop fiddling and open the code in a month, will you remember? Who reads the code, will understand? It is good to try to create this habit already. It can even cause a lot of confusion with typing error and it is very difficult to notice the error

  • T is a Tree pointer, no is node. F a node pointer( best known as child).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.