Given an array of integer (all different from each other), this program creates a BST with the array elements in order to sort them and put them back into the array, using the BST properties.
#include<iostream>
using namespace std;
struct Node
{
int label;
Node* left;
Node* right;
~Node() {
delete left;
delete 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
{
if(!tree) return i;
i = insertIntoArray(arr, tree->left, i);
arr[i] = tree->label;
i++;
i = insertIntoArray(arr, tree->right, i);
return i;
}
int main()
{
Node* maintree;
maintree = NULL;
int num = 7;
int arr[num] = {120, 30, 115, 40, 50, 100, 70};
insertArrayTree(arr, num, maintree); //insert elements into BST
insertIntoArray(arr, maintree, 0); //modify array sorting his elements using the BST
for(int y=0; y<num; y++) cout<< arr[y] << ' ';
return 0;
}
Output:
30 40 50 70 100 115 120
Any advice is welcome.