终于在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;
}
};
本文介绍了一种使用二叉搜索树(BST)解决逆序对问题的方法,并提供了一个具体的C++实现示例。该方法通过插入节点时计算逆序对数量来高效地解决问题。


被折叠的 条评论
为什么被折叠?



