Я пытаюсь написать программу, которая сортирует целочисленные элементы массива, используя двоичное дерево поиска (BST) в качестве вспомогательной структуры данных. Идея состоит в том, что после того, как массив задан, можно использовать BST для сортировки его элемента; например:
если мой массив: {120, 30, 115, 40, 50, 100, 70}
, тогда я создаю BST следующим образом:

Как только у меня будет этот BST, я могу выполнить обход дерева порядка, чтобы коснуться каждого узла по порядку, от самого низкого до самого высокого элемента и изменить массив. Результатом будет отсортированный массив {30, 40, 50, 70, 100, 115, 120}
Я написал этот код, и я не понимаю, где я сделал ошибку. Он компилируется без ошибок, но очевидно, что с ним что-то не так:
#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;
}
Я надеюсь, что мой вопрос достаточно ясен. Буду признателен за любую помощь / совет!
Спасибо:)