Question

I am trying change a pre-written BST that stored INTs to a BST that can store strings.

As far as I can tell my code should work however when ever I try to print the trees' contents it seems to always been null (the tree does not attempt to print because the node I feed it is apparently null).

From other similar questions I have seen its possible that it has something to do with the way my insert works and the values in the node not being assigned correctly. Anyway, Ill post the code for my insert and see how we go.

My nodes are defined as:

typedef struct node *node_ptr;
struct node
{
    char data_item[7];
    node_ptr left;
    node_ptr right;
};

And the insert function:

node_ptr insert(char *n, node_ptr tree)
{
    if(!tree) 
    {
        tree = (node_ptr) malloc(sizeof(struct node));
        strcpy(tree->data_item, n);
        tree->left = tree->right = NULL;
    }

    else if(strcmp(tree->data_item, n) < 0)
    {
        tree->left = insert(n, tree->left);
    }
    else if(strcmp(tree->data_item, n) > 0)
    {
        tree->right = insert(n, tree->right);
    }

    return tree;
}
Was it helpful?

Solution

I haven't seen your code that calls insert, but I'm going to guess that it looks something like:

node_ptr tree = NULL;
insert("abcd", tree);
insert("123", tree);
insert("xyz", tree);

The problem is that tree never gets updated to point to the correct node in the calling function.

If you change it to:

node_ptr tree = NULL;
tree = insert("abcd", tree);
insert("123", tree);
insert("xyz", tree);

it should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top