'Create BST from array of strings

I've been trying to create a functionality in C++ that can implement a BST from an array of strings, but it doesn't do anything at all and I don't understand what might be the problem. It should work recursively with for loop to iterate through all strings in an array.


void insertNode(node* root, std::string name)
{
    if (root == nullptr)
    {
        node* n = new node;
        n->name_ = name;
        root = n;
    }
    else if (root->name_.compare(name) <= 0)
    {
        insertNode(root->right_, name);
    }
    else
    {
        insertNode(root->left_, name);
    }
}

void CreateBST(node_t *& root, const std::vector<std::string> & array)
{   
    for (int i = 0; i < array.size(); i++)
    {
        insertNode(root, array[i]);
    }
}

I've tried to wirte recursive function to create a BST, while comparing strings from an array to set them as nodes.



Solution 1:[1]

The problem with your code is this line

void insertNode(node* root, std::string name)

You need root there to be a node* reference (i.e. node*&) otherwise when you set node to a new value in the function that change is lost to the calling code.

Other possible issues include a typo where you use node_t in the other function, and you need to make sure that the node default constructor is nulling out the two pointers to children because your code assumes those pointers will be null after creation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1