So I am currently ruing into a an aoying situation with my General Tree. I have an object called General Tree that implements a leftmost right sibling Node style. I used this implementation because I would like to have as many nodes as desired. So I have no issue in creating a Tree, the problem arises when I try to copy another tree to my current one. For the sake of this situation let us assume I am only dealing with empty General Trees. So the Node starting begins at the start of the tree I am copying, the parent Node represents where I am to copy into.
I created a representation of how to data insertion works with the nodes, and how it would look in a more familiar graphical way.
So my issue is that I don't want to use static variables but when I recursively call copyFrom(starting->child, parents) and copyFrom(starting->RightSibling, parents) when I arrive at d under the first asterisk (*) there is no way of moving back up one level due to the nature of recursion, a little frustrating. If anyone could help that would be awesome! I also included the code for insertion, it takes a node called parent, finds that node, then inserts the value into newly created child.
void GeneralTree::copyFrom(Node* starting, Node *parent) {
static Node* parents = parent;
if(starting != NULL) {
if(!isalpha(starting->value)){
parents = insert(starting->value, parents);
}
else {
cout << starting->value << " " << parents << endl;
insert(starting->value, parents);
if(starting->child == NULL and starting->RightSibling == NULL) {
parents = parents->parent;
copyFrom(starting->child, parents);
}
}
copyFrom(starting->child, parents);
copyFrom(starting->RightSibling, parents);
}
}
Node* GeneralTree::insert(char value, Node* parent) {
if(parent == NULL and start == NULL) {
Node* temp = new Node;
temp->value = value;
temp->parent = NULL;
temp->last = NULL;
temp->root = true;
start = temp;
retu temp;
}
else if(parent == NULL and start != NULL) {
throw NoParentException();
}
else {
stack<Node*> push;
Node* iter = start;
while(iter != parent) {
if(iter->RightSibling == NULL and iter->child != NULL) {
iter = iter->child;
}
else if(iter->RightSibling != NULL and iter->child != NULL) {
push.push(iter->child);
iter = iter->RightSibling;
}
else if(iter->RightSibling != NULL and iter->child == NULL) {
iter = iter->RightSibling;
}
else {
if(!push.empty()) {
iter = push.top();
push.pop();
}
else {
delete iter;
throw NoParentException();
}
}
}
if(iter != NULL) {
if(iter->child != NULL) {
Node* sibling = new Node();
iter = iter->child;
sibling->parent = iter->parent;
Node* temp = iter->last;
sibling->value = value;
iter->last = sibling;
temp->RightSibling = sibling;
temp = NULL;
iter = NULL;
retu sibling;
}
else {
Node* sibling = new Node();
sibling->value = value;
sibling->parent = iter;
sibling->last = sibling;
iter->child = sibling;
iter = NULL;
retu sibling;
}
}
else {
delete iter;
throw NoParentException();
}
}
}
