I'm tying to create a tree and initialize the tree by duplicating another tree with a stack.
but I ran into issues with Box, Rc and RefCell
both the Tree node and stack need to hold mutable ref to tree nodes.
I can't use Box due to single ownership. I can't use Rc, because I need mutability. How can I do it.
The following cpp code describes what I want to do. in the code, AnotherTree is from another library. I'm forced to use its tree traversal interface using a cursor.
struct Tree {
std::string name;
std::vector<Tree *> children;
};
Tree *root = new Tree();
std::vector<Tree*> stack;
stack.push_back(root);
TreeCursor cursor = AnotherTree.getCursor();
while (true) {
Tree *node = new Tree(cursor);
stack.last().children.push_back(node);
if (cursor.goto_first_child()) {
stack.push(node);
continue;
} else if (cursor.goto_next_sibling()) {
continue;
}
bool retracing = true;
while (retracing) {
if (!cursor.goto_parent()) {
retracing = false;
reached_root = true;
}
else{
stack.pop_back();
}
if (cursor.goto_next_sibling()) {
retracing = false;
}
}
}