2 Replies - 269 Views - Last Post: 07 October 2012 - 02:21 PM Rate Topic: -----

#1 SilverMage  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 43
  • Joined: 11-October 10

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?

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);
	}
}



Is This A Good Question/Topic? 1
  • +

Replies To: Can't properly insert a node into binary tree

#2 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1645
  • View blog
  • Posts: 3,122
  • Joined: 30-May 10

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
(*n)->string = malloc( strlen(s) + 1 );
strcpy( (*n)->string, s );

Was This Post Helpful? 1
  • +
  • -

#3 SilverMage  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 43
  • Joined: 11-October 10

Re: Can't properly insert a node into binary tree

Posted 07 October 2012 - 02:21 PM

View PostSalem_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
(*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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1