Thank you snoopfrogg,
You were right I had to create a new node.
Code:
#include <stdio.h>#include <stdlib.h>
struct Node {
int val;
struct Node *left, *right;
};
void bstSort(int *arr, int n);
struct Node *insert(struct Node *n, int val);
void storeSorted(struct Node *n, int *arr, int *pos);
void bstDestroy(struct Node *n);
int main()
{
int arr[] = { 10, 5, 8, 20, 16, 70, 50, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
bstSort(&arr, n);
for (int ii = 0; ii < n; ii++)
printf("%d\n", arr[ii]);
getchar();
return 0;
}
void bstSort(int *arr, int n)
{
struct Node *root = NULL;
// root = insert(root, arr[0]);
for (int i = 0; i < n; i++)
insert(root, arr[i]);
storeSorted(root, arr, &arr[0]);
bstDestroy(root);
}
struct Node *insert(struct Node *n, int val)
{
if (n == NULL) {
n = malloc(sizeof(struct Node));
(n)->left = NULL;
(n)->val = val;
(n)->right = NULL;
} else {
if (val < n->val)
n->left = insert(n->left, val);
else if (val > n->val)
n->right = insert(n->right, val);
}
return n;
}
void storeSorted(struct Node *n, int *arr, int *pos)
{
if (n != NULL) {
storeSorted(n->left, arr, pos);
arr[*pos] = n->val;
storeSorted(n->right, arr, pos);
}
}
void bstDestroy(struct Node *n)
{
if (n == NULL)
return;
if (n->left != NULL)
bstDestroy(n->left);
if (n->right != NULL)
bstDestroy(n->right);
free(n);
return;
}
Now I have only one problem left.
The code above works and it creates the tree structure as needed, the only thing is that in the storeSorted function the array is sorted but it remains there.
When I go back to the top of the code it is not sorted so I might need to do some more research.