public class Solution {
class TreeNode {
TreeNode left, right;
int val, sum, dup = 1;
public TreeNode (int val, int sum) {
this.val = val;
this.sum = sum;
}
}
public List<Integer> countSmaller(int[] nums) {
Integer[] rst = new Integer[nums.length];
TreeNode root = null;
for (int i = nums.length - 1; i >= 0; i--) {
root = insert(nums[i], root, i, 0, rst);
}
return Arrays.asList(rst);
}
private TreeNode insert(int num, TreeNode node, int index, int prevSum, Integer[] rst) {
if (node == null) {
node = new TreeNode(num, 0);
rst[index] = prevSum;
} else if (num == node.val) {
node.dup++;
rst[index] = prevSum + node.sum;
} else if (num < node.val) {
node.sum++;
node.left = insert(num, node.left, index, prevSum, rst);
} else {
node.right = insert(num, node.right, index, prevSum + node.dup + node.sum, rst);
}
return node;
}
}