一、题目
二、代码
/**
* 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> tree_value;
void recursion(TreeNode* process_node)
{
if(process_node->left) recursion(process_node->left);
if(process_node->right) recursion(process_node->right);
tree_value.push_back(process_node->val);
}
TreeNode* build_tree(vector<int>process_vector,int left,int right)
{
if(left>right) return nullptr;
else
{
int mid=left+(right-left)/2;
TreeNode* temp_node=new TreeNode(process_vector[mid]);
temp_node->left=build_tree(process_vector,left,mid-1);
temp_node->right=build_tree(process_vector,mid+1,right);
return temp_node;
}
}
TreeNode* balanceBST(TreeNode* root)
{
int i,j;
if(root==nullptr) return nullptr;
else recursion(root); //装到容器中
// std::cout<<"size1 "<<tree_value.size()<<std::endl;
// for(i=0;i<tree_value.size();i++) std::cout<<" "<<tree_value[i];
// std::cout<<std::endl;
sort(tree_value.begin(),tree_value.end()); //从小到大排序
// std::cout<<"size2 "<<tree_value.size()<<std::endl;
// for(i=0;i<tree_value.size();i++) std::cout<<" "<<tree_value[i];
// std::cout<<std::endl;
return build_tree(tree_value,0,tree_value.size()-1);
;
}
};