Hello. I am trying to insert a new item to a binary search tree but I can't get my code to work right. Here I am suppose to ask the user for the new class object's data and then store it in the binary search tree. No matter what I try to inert it outputs 'Can't have duplicate code', even if I know it is not there. This is my first time working with binary search trees and my class is accelerated so I don't have the chance to really take my time and learn it on my own like I usually do. I'm just confused on where to go from here and how I can fix my code.
This is what I have in main. This is the code I am having trouble with:
Code:
int main()
{
BinarySearchTree<Stock> tree;
Stock company[23]; //a class to hold data about stocks
string name,
symbol;
double price = 0;
//this is a menu driven program, i only the part of the code I am having trouble with
else if (choice == INSERT)
{
cout << "Enter the new company's name: ";
cin.ignore();
getline(cin, name);
cout << "Enter the new company's symbol: ";
getline(cin, symbol);
cout << "Enter the new company's price: ";
cin >> price;
for (int i = 0; i < 23;)
{
//search for the next empty spot in the class array of objects
while (company[i].getPrice() != 0)
{
i++;
}
if (company[i].getPrice() == 0)
{
company[i].setName(name); //the setters are in the class Stock
company[i].setSymbol(symbol);
company[i].setPrice(price);
tree.insert(company[i]); //outputs 'can't have duplicate code' even if it is not in tree already
}
}
}
Here is what the code looks like to insert an item to the binary search tree. I know there is nothing wrong with this code because my teacher helped the class write it. This code is just here for clarification:
Code:
template <typename T>
void BinarySearchTree<T>::insert(const T& item)
{
insert(root, item);
}
template <typename T>
void BinarySearchTree<T>::insert(Node<T> *&r, const T& item)
{
using namespace std;
if (r == nullptr)
{
r = new Node<T>;
r->info = item;
r->left = nullptr;
r->right = nullptr;
}
else if (item < r->info)
insert(r->left, item);
else if (item > r->info)
insert(r->right, item);
else
cout << "Can't have duplicate code.\n";
}