可惜了,没审题清晰,他要搭建的是BST,不是随便一棵树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// depth count
void read(TreeNode* root, vector<int>& res){
if (root==NULL){
return;
}
res.push_back(root->val);
read(root->left, res);
read(root->right, res);
}
TreeNode* buildTree(vector<int>& res, int start, int end){
if (start>end){
return NULL;
}
int mid = (end-start)/2+start;
TreeNode* root = new TreeNode(res[mid]);
root->left = buildTree(res, start, mid-1);
root->right = buildTree(res, mid+1, end);
return root;
}
//A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1
// 左右子树深度差为《=1
TreeNode* balanceBST(TreeNode* root) {
vector<int> res;
read(root, res);
sort(res.begin(), res.end());
return buildTree(res, 0, res.size()-1);
}
};