The first problem is here:
Tree* arr = (Tree*) malloc(TreeSize(root) * sizeof(Tree));
This gives you "an array" of Tree
elements but what you want is "an array" of pointers to Tree
elements.
So change it to:
Tree** arr = malloc(TreeSize(root) * sizeof *arr);
The second problem is here:
void BSTtoArr(Tree * root,Tree* arr[],int i) {
if(root == NULL) return;
BSTtoArr(root->left,arr,i+1); <---- i+1
v[i] = root->data; <---- data ???
BSTtoArr(root->right,arr,i+1); <---- i+1
}
You pass the same array index to the left and the right recursion so the recursive calls will write to the same index. You need to make sure that every time you write to the array, it's done with a new index value. To do that you can pass a pointer to the index variable and update the index when a new element is inserted in the array.
Further, you to try to save root->data
into the array but the array is supposed to hold the nodes - not the node data.
To solve this you can do:
void BSTtoArr(Tree * root, Tree* arr[], int* i) {
if(root == NULL) return;
BSTtoArr(root->left, arr, i);
v[*i] = root;
*i = *i + 1;
BSTtoArr(root->right, arr, i);
}
and call it like:
Tree** arr = malloc(TreeSize(root) * sizeof *arr);
int i = 0;
BSTtoArray(root, arr, &i);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…