I wrote a function to read all the elements in order from a binary search tree and then put them inside a vector, however I get an error at the line where I declare my new vector and I'm not sure what's wrong.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void _to_vector(bst_node* ptr, std::vector<T>* V, int& index){
if (ptr == nullptr)
return;
else{
_to_vector(ptr->left, V, index);
V[index++] = ptr->val;
_to_vector(ptr->right, V, index);
}
}
std::vector<T>* to_vector() {
std::vector<T>* V = new T;
int index = 0;
_to_vector(root,V,index);
return V;
}
std::vector<int> v;
int i = 0;
v[i++] = 0; // <-- this
v[i++] = 0; // <-- and this is not how you grow a vector
//this is:
v.push_back(0);
v.push_back(0);