终于在bst标签下找到一个lz能用bst做的出来的题目,泪目跪谢感谢扶起了我的自尊心,直接上代码,很简单的,就是逆序对的求法。
class Solution {
public:
struct node{
int num, count;
node *l, *r;
node(int num): num(num), count(0), l(NULL), r(NULL) {}
};
int Insert(node *&root, int num){
int ans = 0;
if(root == NULL) root = new node(num);
else{
if(num >= root->num){
ans += num == root->num? root->count : root->count + 1;
ans += Insert(root->r, num);
}
else{
root->count++;
ans += Insert(root->l, num);
}
}
return ans;
}
vector<int> countSmaller(vector<int>& nums) {
int n = (int)nums.size();
vector<int> ans(n, 0);
node* root = NULL;
for(int i = n-1; i>=0; i--){
ans[i] = Insert(root, nums[i]);
}
return ans;
}
};