I am writing a binary tree, started getting errors, so I’ve removed all my templating, but it still won’t compile, stumped by my final error!
Writing a recursive add function, but not sure how to add my new dataClass to my tree when it finds an empty node
#pragma once
#include <cstring>
typedef dataClass T;
//template <class T>
class treeNode
{
private:
treeNode* _greaterNode;
treeNode* _lessNode;
T _data;
public:
treeNode(T data);
void add(T data);
void del(T data);
};
//template <class T>
treeNode/*<T>*/::treeNode(T data)
{
_data = data;
_greaterNode = _lessNode = NULL;
}
//template <class T>
void treeNode/*<T>*/::add(T data)
{
if(_data == NULL)
{
// add here
this = new treeNode(data);
}
else if(data > _data)
{
// data is bigger go to greater
this->_greaterNode->add(data);
}
else if(data < _data)
{
// data is lower go to less than
this->_lessNode->add(data);
}
else
{
// data the same, throw exception
}
}
It’s breaking on:
if(_data == NULL)
{
// add here
this = new treeNode(data);
}
You can not assign to
this! You could assing to*this, like in*this = treenode(data);, but that could probably lead to other errors as the node pointer would be overwritten.Why not simply set
_datato the parameterdata?Also, when doing the recursive call you should create the links if they do not exist: