I would like to convert an AVL tree to an array by inorder and then return it by the function GetArray, for some reason the code isn't working. It only stores the first data.
void InsertInArray(Node<T>* node,int int index,T** array)
{ if(node==NULL)
return;
InsertInArray(node->LeftSon,index,array);
array[index++]=node->data;
InsertInArray(node->RightSon,index,array);
}
T** GetArray ()
{
T** array=new T*[this->size];
InsertInArray(this->head,0,array);
return array;
}
//The data is of type T*
UPDATE: THE FOLLOWING CODE ALSO WORKED!
Your code saves every data in i-th depth on the single element array[i]
and thus fails.
We must always push-back each data to array
as the last element.
The most simple way to do it is using std::vector::push_back
.
Although I don't know the whole code of your project, I expect following code will work fine for you:
#include <vector>
void InsertInArray(Node<T>* node, std::vector<T>& array)
{
if(node==NULL){
return;
}
InsertInArray(node->LeftSon, array);
array.push_back(node->data);
InsertInArray(node->RightSon, array);
}
std::vector<T> GetArray()
{
std::vector<T> array;
InsertInArray(this->head, array);
return array;
}