It's assigned from me to implement a tree ADT with insert function with this definition
Insert (int val, char loc, int otherVal):
,where the val is a one of the childs if the the root is not null, location is either left or right , the other val is for the child of the val and it will be the opposite of the loc,The template class node should have data integer, Left child pointer and right child pointer and I implemented them, my problem is while writting the insert function in the BTS class it bring me this error:
Exception thrown: read access violation.
**this** was nullptr.
What I have tried:
<pre>void Tree::Insert(int val, char c, int OtherVal)
{
if (Root->getdata()== NULL)
{
Root->setdata(val);
Node* new5 = new Node();
if (c == 'L')
{
Root->setright(new5);
}
else if (c == 'R')
{
Root->setleft(new5);
}
}
else
{
Node* new1 = new Node();
Node* new2 = new Node();
new1->setdata(val);
new2->setdata(OtherVal);
if (c == 'L')
{
Root->setleft(new1);
new1->setright(new2);
}
else if (c == 'R')
{
Root->setright(new1);
new1->setleft(new2);
}
}
}
the node class:
#include "Node.h"
Node::Node()
{
data = 0;
left = right = nullptr;
}
Node::Node(int val)
{
data = val;
left = right = nullptr;
}
void Node::setdata(int d)
{
data = d;
}
int Node::getdata()
{
return data;
}
void Node::setleft(Node* p)
{
left = p;
}
Node*& Node::getleft()
{
return left;
}
void Node::setright(Node* p)
{
right = p;
}
Node*& Node::getright()
{
return right;
}
Search Function:
Node* Tree::SearchMax()
{
return FindMax(Root);
}
Node* Tree::FindMax(Node* subroot)
{
if (subroot == nullptr) return subroot;
Node* temp = subroot;
Node* lmax = FindMax(temp->getleft());
Node* rmax = FindMax(temp->getright());
if (lmax->getdata() > temp->getdata())
{
temp = lmax;
}
if (rmax->getdata() > temp->getdata())
{
temp = rmax;
}
return temp;
}
Print Function:
void Tree::print()
{
return printPreorder(Root);
}
void Tree::printPreorder(Node*subroot)
{
if (subroot != nullptr)
{
cout << Root->getdata() << " ";
printPreorder(subroot->getleft());
printPreorder(subroot->getright());
}
}
int main()
{
Tree t;
t.Insert(5, 'L', 20);
t.print();
return 0;
}