Hi I am trying to write a binary tree in c++, but am having some difficulties. Here is my code when I construct the object I set my left and right child to be nullptr and then when I try to insert a new element on the right child in the insert I get the error: Process finished with exit code -1073741819 (0xC0000005)
Here is my code for the tree:
template <class T>
class Binary {
T node;
Binary<T>* leftChild;
Binary<T>* rightChild;
public:
Binary<T>(T node);
T getNode();
Binary<T> left();
Binary<T> right();
void insert(T el);
void print();
};
And my insert method:
template <class T>
Binary<T>::Binary(T node){
this->node = node;
this->leftChild = nullptr;
this->rightChild = nullptr;
}
template <class T>
void Binary<T>::insert(T el){
if(el < node){
if(leftChild != nullptr){
leftChild->insert(el);
} else {
leftChild = new Binary<T>(el);
}
} else {
if(rightChild != nullptr){
rightChild->insert(el);
} else {
rightChild = new Binary<T>(el);
}
}
}
I get the error on this line:
rightChild = new Binary<T>(el);
But it's very strange because I can do something like:
Binary<T>* ptr = new Binary<T>(el);
Without any problem so I am thinking that maybe its because I am assigning a new pointer to a nullptr, but am not sure what the problem is.
Thank you for your help!
EDIT: Here is the full main.cpp file code:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
template <class T>
class Binary {
T node;
Binary<T>* leftChild = nullptr;
Binary<T>* rightChild = nullptr;
public:
Binary<T>(T node);
T getNode();
void insert(T el);
void print();
};
template <class T>
T Binary<T>::getNode() {
return node;
}
template <class T>
void Binary<T>::insert(T el){
if(el < node){
if(leftChild != nullptr){
leftChild->insert(el);
} else {
leftChild = new Binary<T>(el);
}
} else {
printf("this=%p\n", this);
if(rightChild != nullptr){
rightChild->insert(el);
} else {
this->rightChild = new (nothrow) Binary<T>(el);
}
}
}
template <class T>
void Binary<T>::print(){
queue<T> childQueue;
childQueue.push(this->node);
if(leftChild != nullptr){
childQueue.push(leftChild->node);
leftChild->print();
}
if(rightChild != nullptr){
childQueue.push(rightChild->node);
leftChild->print();
}
while(!childQueue.empty()){
cout << childQueue.front();
childQueue.pop();
}
}
template <class T>
Binary<T>::Binary(T node) : node(node), leftChild(nullptr), rightChild(nullptr){
}
int main() {
Binary<int> tree(0);
tree.insert(1);
// tree.insert(3);
// tree.insert(5);
// tree.insert(4);
// tree.insert(2);
tree.print();
return 0;
}
It was the print method I had copied the incorrectly and was accessing the leftChild instead of the rightChild in the leftChild != nullptr check.
User contributions licensed under CC BY-SA 3.0