#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
void inorder(TreeNode *root)
{
if (!root)
return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
TreeNode *sortedArrayToBST(vector<int> arr, int start, int end)
{
// base cases
// empty array
if (start > end)
return NULL;
// single element array
if (start == end)
return new TreeNode(arr[start]);
// find the middle of the array
int mid = start + (end - start + 1) / 2;
TreeNode *root = new TreeNode(arr[mid]);
// recursively create left subtree
// from the left part[start,mid-1]
root->left = sortedArrayToBST(arr, start, mid - 1);
// recursively create left subtree from
// the right part[mid+1, end]
root->right = sortedArrayToBST(arr, mid + 1, end);
return root;
}
int main()
{
int n;
cout << "Enter array size\n";
cin >> n;
vector<int> arr(n);
cout << "Enter the elements in sorted order(increasing)\n";
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << "Creating self-balancing BST from the sorted list\n";
TreeNode *root = sortedArrayToBST(arr, 0, arr.size() - 1);
cout << "height balanced BST created ...\n";
cout << "root of the BST created is: " << root->val << endl;
cout << "Inorder traversal of the BST\n";
inorder(root);
cout << endl;
return 0;
}
Output
Enter array size
5
Enter the elements in sorted order(increasing)
1 2 3 4 5
Creating self-balancing BST from the sorted list
height balanced BST created ...
root of the BST created is: 3
Inorder traversal of the BST
1 2 3 4 5
0 Comments