I'm trying to write a program that sorts integer elements of an array, using a Binary Search Tree(BST) as support data structure. The idea is that once the array is given, then it is possible to use a BST to sort his element; for example:
if my array is: {120, 30, 115, 40, 50, 100, 70}
then I build a BST like this:
Once I have this BST, I can do an inorder tree traversal to touch every node in order, from the lowest to the highest element and modify the array. The result would be a sorted array {30, 40, 50, 70, 100, 115, 120}
I wrote this code and I don't understand where is the error I made. It compiles without any error, but obviously there is something wrong with it:
#include<iostream>
using namespace std;
struct Node
{
int label;
Node* left;
Node* right;
};
void insertSearchNode(Node* &tree, int x) //insert integer x into the BST
{
if(!tree){
tree = new Node;
tree->label = x;
tree->right = NULL;
tree->left = NULL;
return;
}
if(x < tree->label) insertSearchNode(tree->left, x);
if(x > tree->label) insertSearchNode(tree->right, x);
return;
}
void insertArrayTree(int arr[], int n, Node* &tree) //insert the array integer into the nodes label of BST
{
for(int i=0; i<n; i++){
insertSearchNode(tree, arr[i]);
}
return;
}
int insertIntoArray(int arr[], Node* &tree, int i) //insert into the array the node label touched during an inorder tree traversal
{
i=0;
if(!tree) return 0;
i += insertIntoArray(arr, tree->left, i) +1;
arr[i] = tree->label;
i += insertIntoArray(arr, tree->right, i) +1;
return i;
}
int main()
{
Node* maintree;
maintree = NULL;
int num;
cin>>num;
int arr[num];
for(int i=0; i<num; i++){ //initialize array with num-elements
cin>>arr[i];
}
insertArrayTree(arr, num, maintree); //insert elements into BST
int index;
insertIntoArray(arr, maintree, index); //modify array sorting his elements using the BST
for(int y=0; y<num; y++) cout<< arr[y] << ' ';
return 0;
}
I hope that my question is clear enough. Any help/advice would be appreciated!
Thanks :)

insertIntoArrayimmediately set itsiargument to0?insertIntoArray. You forgot to check ifx == tree->labelininsertSearchNodealso.