I am working on an avl tree with strings as keys. The print statements indicate that the insert is happening but in the testing function it reports that the left and right nodes of the root remain null.
Here is my avl tree code:
#include "AVLAdt.h"
void printVal(node * toPrint){
printf("\n node value: %s\n", toPrint->nodeValue);
}
node * search(node * root, char * searchVal){
if(isExternal(root) == 1) return NULL;
if(strcmp(searchVal,root->nodeValue)<0){
return(search(root->leftNode,searchVal));
}
else if(strcmp(searchVal,root->nodeValue)==0){
return(root);
}
else {
return(search(root->rightNode,searchVal));
}
}
/*initialize a node*/
node * initNode(char * toAdd){
node * newNode = malloc(sizeof(node));
strcpy(newNode->nodeValue, toAdd);
newNode->leftNode = NULL;
newNode->rightNode = NULL;
newNode->height = 1;
return newNode;
}
/*function to insert a new node into tree and rebalance if necessary*/
node * insert(node * root, char * newValue){
if(root == NULL){
printf("\n Inserting %s. \n", newValue);
return(initNode(newValue));
}
else{
if(strcmp(newValue,root->nodeValue)<0){
printf("go left");
insert(root->leftNode, newValue);
}
else if(strcmp(newValue,root->nodeValue)>0){
printf("go to right node of %s", root->nodeValue);
insert(root->rightNode, newValue);
}
else{
root->count++;
return (root);
}
}
Testing program:
#include "AVLAdt.h"
int main(){
node * root = NULL;
char * testString = malloc(sizeof(char)*50);
strcpy(testString, "aa");
char * testString1 = malloc(sizeof(char)*50);
strcpy(testString1, "bb");
printf("does it try to insert?");
root = insert(root, testString);
root = insert(root, testString1);
printVal(root);
if(getRight(root) == NULL) printf("right is null");
else{
printf("right is");
printVal(getRight(root));
}
if(getLeft(root) == NULL) printf("left is null");
else{
printf("left is");
printVal(getRight(root));
}
return(0);
}
The code returns that both left and right nodes of "aa" are null. Why is this?
In the
search()
function, not sure why you doIf the
node
is external, i.e. doesn't have any leaves, you'd still want to compare itsnodeValue
to thesearchVal
and returnroot
in case of match.In
initNode()
function, next-to-the-last line should beinstead of
Also, it seems to me that in the
insert()
function,initNode()
's return value should be assigned toroot
to store the pointer to the newly addednode
in the tree, i.e. you should have:instead of
(you also don't have to put return value in parenthesis by the way).
WhozCraig has already pointed out issue with the return values of recursive
insert()
calls.