0

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.

4
  • For changes to root to have an effect outside insertNode it needs to be node**. Commented Apr 5, 2022 at 16:08
  • 2
    FYI, you can use comparison operators: <, >, ==, !=, <=, >=, with std::string instead of the compare() method. IMHO, easier to read using the comparison operators. Commented Apr 5, 2022 at 16:23
  • also last compare is obsolete. Commented Apr 5, 2022 at 16:37
  • @Alessa when I've wrote last compare is obsolete I meant condition is obsolete since is covered by earlier if (you are in else section of it), code below is still needed. Commented Apr 5, 2022 at 16:46

1 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.