Hi I've been trying to code a bst based upon this link below:
http://www.stanford.edu/~blp/avl/libavl.html/BST_operations.c.txt

I've adopted a similar strategy, whilst making some modifications, however for me I'm having a problem in that every time I go to add a new node to the bst, the root is always null, and thus no to *bst occur once the insert function has terminated.

I think I could use a pointer to a pointer to fix this, but what I don't understand is how the code in the above link works, when mine is basically the same.

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node{
	struct node *left, *right;
	char *data;
	int count;
};


struct bst{
	struct node *root;
};


bst *bst_create( ){
	struct bst *bstTree;

	if ((bstTree = (struct bst *)malloc(sizeof(struct bst))) != NULL) {
		bstTree->root = NULL;
		return bstTree;
	}

}


node *create_node(char *data){
	struct node *tempNode;

	if ((tempNode = (struct node *)malloc(sizeof(struct node))) != NULL) {
		tempNode->data = data;
		tempNode->left = NULL;
		tempNode->right = NULL;
		tempNode->count = 0;
		return tempNode;
	}
}

int bst_insert(bst *bstTree, char *data){

	struct bst *tempBst = bstTree;
	struct tldnode *current = bstTree->root;

	struct tldnode *newNode = create_node(data);

	if ( current == NULL){
		current = newNode;
		return 1;	
	}
	for ( ; ;){

		cmp = strcmp(data,current->data);

		if (cmp == 0){
			current->count++;
			return 1;
		}		


		if (cmp < 0)
			current = current->left;

		else
			current = current->right;


		if (current == NULL)
			break;
	}


	if (cmp < 0)
		current->left = newNode;
	else
		current->right = newNode;

	return 1;

}

Also heres the insert function for the above link:

void **
bst_probe (struct bst_table *tree, void *item)
{
  struct bst_node *p, *q; /* Current node in search and its parent. */
  int dir;                /* Side of |q| on which |p| is located. */
  struct bst_node *n;     /* Newly inserted node. */

  assert (tree != NULL && item != NULL);

  for (q = NULL, p = tree->bst_root; p != NULL; q = p, p = p->bst_link[dir])
    {
      int cmp = tree->bst_compare (item, p->bst_data, tree->bst_param);
      if (cmp == 0)
        return &p->bst_data;
      dir = cmp > 0;
    }

  n = tree->bst_alloc->libavl_malloc (tree->bst_alloc, sizeof *p);
  if (n == NULL)
    return NULL;

  tree->bst_count++;
  n->bst_link[0] = n->bst_link[1] = NULL;
  n->bst_data = item;
  if (q != NULL)
    q->bst_link[dir] = n;
  else
    tree->bst_root = n;

  return &n->bst_data;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.