-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_315_41.cpp
More file actions
55 lines (50 loc) · 1.14 KB
/
LeetCode_315_41.cpp
File metadata and controls
55 lines (50 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* @lc app=leetcode id=315 lang=cpp
*
* [315] count of Smaller Numbers After Self
* T(n) = O(N)
* S(n) = O(N)
*/
class Solution
{
public:
vector<int> countSmaller(vector<int> &nums)
{
TreeNode *root = NULL;
vector<int> res(nums.size());
for (int i = nums.size() - 1; i >= 0; i--)
res[i] = bstInsert(root, nums[i]);
return res;
}
private:
struct TreeNode
{
int val;
int sum;
TreeNode *left;
TreeNode *right;
TreeNode(int v, int s) : val(v), sum(s), left(NULL), right(NULL) {}
};
int bstInsert(TreeNode* &root,
int val)
{
int count = 0;
if (root == NULL)
{
root = new TreeNode(val, 0);
return 0;
}
if (val < root->val)
{
root->sum++;
count = bstInsert(root->left, val);
}
else
{
count = bstInsert(root->right, val) +
root->sum +
(root->val < val ? 1 : 0);
}
return count;
}
};