I've always wanted to make a binary tree, so here I am experimenting, and I've bumped into a wall, more specificly , outputting the binary tree with the operator <<.Currently what it does is, printing the reference of that value I assume, and if I try to change obj to *obj,I get errors.(I know that this way ,the current program will output only the root value).
Bonus question :how to make the writeStuff() function output the whole tree correctly ?
My code:
#include <iostream>
#include <vector>
class binFa
{
char value;
binFa *righElem;
binFa *leftElem;
public:
binFa(char elem) : value(elem)
{
rightElem = NULL;
leftElem = NULL;
}
binFa(const binFa &fa)
{
value = fa.value;
rightElem = new binFa(fa.rightElem->value);
leftElem = new binFa(fa.leftElem->value);
}
binFa &operator<<(char elem)
{
if (elem == '0')
leftElem = new binFa(elem);
else
rightElem = new binFa(elem);
return *this;
}
void writeStuff(binFa *fa)
{
std::cout << fa->value << " ";
if (fa->rightElem != NULL || fa->leftElem != NULL)
{
writeStuff(fa->leftElem);
writeStuff(fa->rightElem);
}
}
std::ostream &operator<<(std::ostream &os)
{
os << this->value;
return os;
}
};
int main()
{
binFa *obj = new binFa('/');
*obj << '0' << '1' << '0';
std::cout << obj;
obj->writeStuff(obj);
delete obj;
return 0;
}