/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> nums;
void track_back(TreeNode* cur)
{
if(cur == nullptr) return;
track_back(cur->left);
nums.push_back(cur->val);
track_back(cur->right);
return;
}
TreeNode* make_tree(vector<int> &nums , int left ,int right)
{
if(left > right) return nullptr;
int mid = left + (right - left)/2;
TreeNode* new_root = new TreeNode(nums[mid]);
new_root->left = make_tree(nums , left ,mid-1);
new_root->right = make_tree(nums , mid+1 ,right);
return new_root;
}
TreeNode* balanceBST(TreeNode* root) {
track_back(root);
return make_tree(nums,0,nums.size()-1);
}
};