I've been trying to implement a tree class in c++ but I can't manage to make it work. I have implemented it like this:
class Tree {
private:
int root;
vector<Tree> children;
public:
Tree(int root);
int getRoot();
vector<Tree> getChildren();
void addChild(Tree& child);
void printTree();
bool isTreePresent(Tree element, queue<Tree> q);
};
With these associated functions:
Tree::Tree(int root){
this->root = root;
}
int Tree::getRoot(){
return root;
}
vector<Tree> Tree::getChildren(){
return this->children;
}
void Tree::addChild(Tree& child){
children.push_back(child);
}
void Tree::printTree(){
queue<Tree> nextToPrint;
cout << "Edges:" << endl;
nextToPrint.push(*this);
while (!nextToPrint.empty()) {
for (int i = 0; i < nextToPrint.front().getChildren().size(); i++){
nextToPrint.push(nextToPrint.front().getChildren()[i]);
cout << "{" << nextToPrint.front().getRoot() << ", " << nextToPrint.front().getChildren()[i].getRoot() << "}" << endl;
}
nextToPrint.pop();
}
cout << endl;
}
As you can see, I've define a tree (as well as a node) as an int value and a vector of its children. It works a bit, but when I try to add children to already added element like this:
Tree a(5);
Tree tmp1(1);
Tree tmp2(2);
Tree tmp3(3);
a.addChild(tmp1);
tmp1.addChild(tmp2);
a.addChild(tmp3);
a.printTree();
It doesn't work. My tree is only made of a, the root, and 2 children : tmp1 and tmp3. At least that is what is displayed by my printTree function. When I use printTree on tmp1 though, it does display the tmp2 child.
Is this a problem with my print function ? Or is it a problem with my class in general ?
I have tried to make the children vector a vector of addresses of Trees, but it still didn't worked. I also tried to add children in the right order and it worked:
// This order works
tmp1.addChild(tmp2);
a.addChild(tmp1);
a.addChild(tmp3);
Unfortunately, I need to add children to already existing children for what I plan to do with these trees (I need them to make a spanning tree of a graph).