So I have created a Binary Search Tree (BST) by placing nodes into a vector. These nodes store 3 values, a user input int
ID, a user input int
age, and a user string
input name.
When inserting these nodes into the vector, they are stored going in ascending order.
Currently I'm working with two nodes.
104 10 Bob
102 11 Steve
When pushing back the first node, there are no problems; however, when attempting to push back the second node, I am getting an out_of_bounds error thrown by the vector class.
I believe something is wrong with my insert function when attempting to switch the positions of these two nodes, however I can't tell exactly where the issue lies.
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int index;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree;
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
cout << "Please enter the ID number, age and name" << endl;
cin >> ID >> AGE >> NAME;
Node *tree = new Node(ID, AGE, NAME);
if (index == 0)
{
binaryTree.push_back(*tree);
index++;
}
if (index > 0)
{
if ((binaryTree.at(index - 1).ID) < ID)
{
binaryTree.push_back(*tree);
index++;
}
}
if (index > 0)
{
if ((binaryTree.at(index - 1).ID) > ID)
{
Node *temp = new Node();
*temp = binaryTree.at(index - 1);
binaryTree.at(index - 1) = *tree;
binaryTree.at(index) = *temp;
index++;
}
}
cout << "Added! Size: " << binaryTree.size() << endl;
cout << " " << endl;
start();
Would appreciate the help! Thanks!