I am tasked with storing a binary tree within a vector. Within each node is stored an int ID, int Age, and a string name.
The nodes are stored and organized within the vector by ID.
When storing the binary tree within a vector, I am using the algorithm 2i and 2i+1 to dictate a node's left and right child respectively.
I have managed to create an insert method that I believe satisfies these conditions and inserts a node into a vector, however, after attempting to insert these nodes into the vector
50 21 Tim
75 22 Steve
I notice that it is not actually inserting these nodes into the vector.
I placed a line that prints the index after insertion, and I have realized that after the first insertion, index no longer updates.
An example Running the insert method using this example
Is there something wrong with my insert() method?
Here is my code.
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
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(30);
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 == 2)
{
Delete();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
int root = 1;
bool success = false;
cout << "Please enter the ID number, age and name:" << endl;
do
{
cin >> ID >> AGE >> NAME;
} while (ID < 0);
Node *tree = new Node(ID, AGE, NAME);
if (index == 0)
{
binaryTree[1] = *tree;
}
if (index > 0)
{
do
{
if (tree->ID > binaryTree.at(root).ID)
{
root = 2 * root + 1;
}
if (tree->ID < binaryTree.at(root).ID)
{
root = 2 * root;
}
if (binaryTree.at(root).ID == NULL)
{
binaryTree.at(root) = *tree;
cout << "Added!" << endl;
cout << "Vector size: " << binaryTree.size() << endl;
success = true;
}
} while (!success);
}
index++;
cout << index << endl;
delete tree;
start();
}
EDIT: I realized that I failed to check against index, so I changed it from '=' to '==' comparison to start the loop. However, Now I am getting a _Xout_of_range("invalid vector subscript"); exception thrown by the vector class
Here is the error.

