I am trying to traverse a templated AVLtree with a key value pair and return a vector of all the values.
When using a cout statement, I can tell that the function is correctly traversing the tree and it will return all values in the tree. However, when I try to add this to a vector and use it in another part of my program, only the root node has been stored.
vector<s> treeTraversal(){
return treeTraversal(root);
}
vector<s> treeTraversal(AVLNode<t, s> *node ){
vector<s> temp;
if(node != nullptr){
treeTraversal(node -> left);
treeTraversal(node -> right);
temp.push_back(node -> vectorToBe);
}
return temp;
}
I am intending to store all the returned values in a vector so I can access them in a later part of my program
I'd try something like this. You'll avoid creating a ton of vector<s>
s in the stack.
vector<s> treeTraversal(){
vector<s> result;
treeTraversal(root, result);
return result;
}
void treeTraversal(AVLNode<t, s> *node, vector<s>& visited ){
if(node != nullptr){
treeTraversal(node -> left, visited);
treeTraversal(node -> right, visited);
visited.push_back(node->vectorToBe);
}
}