// C++ Code
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val) : val(val), left(nullptr), right(nullptr) {}
};
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBST(nums, 0, nums.size() - 1);
}
TreeNode* sortedArrayToBST(vector<int>& nums, int left, int right) {
if (left > right) {
return nullptr;
}
int mid = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = sortedArrayToBST(nums, left, mid - 1);
root->right = sortedArrayToBST(nums, mid + 1, right);
return root;
}
// Helper function to print the tree (in-order traversal)
void inOrderTraversal(TreeNode* root) {
if (root == nullptr) {
return;
}
inOrderTraversal(root->left);
cout << root->val << " ";
inOrderTraversal(root->right);
}
};
int main() {
Solution solution;
vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
TreeNode* root = solution.sortedArrayToBST(nums);
solution.inOrderTraversal(root); // Print the sorted BST
return 0;
}