#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class TreeNode {
public :
int value;
TreeNode* left;
TreeNode* right;
TreeNode( int val) {
value = val;
left = right = nullptr;
}
} ;
// Function to build a balanced BST from a sorted array
TreeNode* buildBalancedBST( vector< int > & arr, int start, int end) {
// Base case: if start > end, return nullptr (no nodes left to insert)
if ( start > end) {
return nullptr;
}
// Find the middle element and make it the root
int mid = ( start + end) / 2 ;
TreeNode* root = new TreeNode( arr[ mid] ) ;
// Recursively build the left and right subtrees
root- > left = buildBalancedBST( arr, start, mid - 1 ) ; // Left subtree
root- > right = buildBalancedBST( arr, mid + 1 , end) ; // Right subtree
return root;
}
// In-order traversal to print the tree
void inorderTraversal( TreeNode* root) {
if ( root ! = nullptr) {
inorderTraversal( root- > left) ;
cout << root- > value << " " ;
inorderTraversal( root- > right) ;
}
}
int main( ) {
vector< int > values = { 10 , 5 , 15 , 3 , 7 , 20 } ; // Input array
// Sort the array first to ensure balanced tree
sort( values.begin ( ) , values.end ( ) ) ;
// Build the balanced BST
TreeNode* root = buildBalancedBST( values, 0 , values.size ( ) - 1 ) ;
// Print the in-order traversal of the tree (should be sorted)
inorderTraversal( root) ;
cout << endl;
return 0 ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY2xhc3MgVHJlZU5vZGUgewpwdWJsaWM6CiAgICBpbnQgdmFsdWU7CiAgICBUcmVlTm9kZSogbGVmdDsKICAgIFRyZWVOb2RlKiByaWdodDsKCiAgICBUcmVlTm9kZShpbnQgdmFsKSB7CiAgICAgICAgdmFsdWUgPSB2YWw7CiAgICAgICAgbGVmdCA9IHJpZ2h0ID0gbnVsbHB0cjsKICAgIH0KfTsKCi8vIEZ1bmN0aW9uIHRvIGJ1aWxkIGEgYmFsYW5jZWQgQlNUIGZyb20gYSBzb3J0ZWQgYXJyYXkKVHJlZU5v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