void insertNodeCaseSens(struct node** n, char* s)
{
if(*n == NULL)
{
*n = (struct node*)malloc(sizeof(struct node));
(*n)->string = s;
(*n)->left = NULL;
(*n)->right = NULL;
}
else if(strcasecmp(s, (*n)->string) < 0)
{
insertNodeCaseSens(&(*n)->left, s);
printf("%s\n", (*n)->left->string);
}
else
{
insertNodeCaseSens(&(*n)->right, s);
printf("%s\n", (*n)->right->string);
}
}
Can't properly insert a node into binary tree
Page 1 of 12 Replies - 126 Views - Last Post: 07 October 2012 - 02:21 PM
#1
Can't properly insert a node into binary tree
Posted 07 October 2012 - 01:47 PM
Hey, I'm having some trouble inserting strings into a BST I've implemented, I followed this tutorial's insert method but when I use the version I made for strings, for some reason, the root will be overwritten by the very last string I input, as well as the string of the right node. What do I need to change in order to make the method actually create a working BST?
Replies To: Can't properly insert a node into binary tree
#2
Re: Can't properly insert a node into binary tree
Posted 07 October 2012 - 02:13 PM
> 06 (*n)->string = s;
s is just a pointer, so what are you exactly storing here?
If ultimately, s is just a pointer to some local variable that gets re-used, then all your BST entries end up pointing at the same thing.
Try something like
s is just a pointer, so what are you exactly storing here?
If ultimately, s is just a pointer to some local variable that gets re-used, then all your BST entries end up pointing at the same thing.
Try something like
(*n)->string = malloc( strlen(s) + 1 ); strcpy( (*n)->string, s );
#3
Re: Can't properly insert a node into binary tree
Posted 07 October 2012 - 02:21 PM
Salem_c, on 07 October 2012 - 02:13 PM, said:
> 06 (*n)->string = s;
s is just a pointer, so what are you exactly storing here?
If ultimately, s is just a pointer to some local variable that gets re-used, then all your BST entries end up pointing at the same thing.
Try something like
s is just a pointer, so what are you exactly storing here?
If ultimately, s is just a pointer to some local variable that gets re-used, then all your BST entries end up pointing at the same thing.
Try something like
(*n)->string = malloc( strlen(s) + 1 ); strcpy( (*n)->string, s );
Oh my god, how did I overlook that?! AGH! My code works now, time to perform cleanup! I can't believe it was such a tiny thing. Thank you very much, Salem, you are quite the savior.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote




|