I am stuck on one question of Data Structure and algorithm. The question is about how to construct a Binary Search Tree (BST) of minimum height from a given BST. For more clarity, here is the link to the question
Convert a normal BST to Balanced BST
Here is my solution:
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int data)
{
this->val = data;
this->right = NULL;
this->left = NULL;
}
};
void inorder_traversal(TreeNode *root, vector<TreeNode*> &v1)// Inorder traversal of tree
{
if(!root)
return;
inorder_traversal(root->left, v1);
v1.push_back(root);
inorder_traversal(root->right, v1);
}
TreeNode* conversion(vector<TreeNode*> &v1, int start, int end) //
{
if(start > end)
return NULL;
int mid = (start + end) / 2;
//-----------Doubt Part----------//
v1[mid]->left = conversion(v1, start, mid - 1);// I think this part is not working well
v1[mid]->right = conversion(v1, mid + 1, end);
return v1[mid];
//-------------------------------//
}
void solve(TreeNode *root) // main function
{
vector<TreeNode*> v1;
inorder_traversal(root, v1);// function to get the inorder traversal of the given tree
int n = v1.size();
cout << v1.size();
TreeNode *l = conversion(v1, 0, n);// function to convert given tree to min height BST
for(auto itr : v1)
cout << itr->val << " ";
}
int height(TreeNode *root) // function to calculate the height of the BST tree
{
if(!root)
return 0;
int hl = height(root->left);
int hr = height(root->right);
return 1 + max(hl, hr);
}
int main()
{
TreeNode *root = new TreeNode(10);
root->left = new TreeNode(8);
root->left->left = new TreeNode(7);
root->left->left->left = new TreeNode(6);
root->left->left->left->left = new TreeNode(5);
int height1 = height(root);
solve(root);
int height2 = height(root);
cout << "Initial height before the conversion :" << height1 << "\n";
cout << "Final height after the conversion :" << height2 << "\n";
return 0;
}
Basically, I am not getting any output after executing the current code, and I figured that the problem has occurred because of the Doubt part of my code.
Can anyone please help me with this code?