Skip to content

Commit 4ab075f

Browse files
authored
Merge pull request chipbk10#109 from chipbk10/Tree
Solve Problem 315 - Count of smaller numbers after self
2 parents f06c7db + f6a557f commit 4ab075f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package tree;
2+
3+
import java.util.LinkedList;
4+
import java.util.List;
5+
6+
public class Problem315_CountOfSmallerNumbersAfterSelf {
7+
8+
9+
// TODO: still wrong
10+
public List<Integer> countSmaller(int[] A) {
11+
LinkedList<Integer> res = new LinkedList<>();
12+
int n = A.length;
13+
if (n == 0) return res;
14+
15+
TreeNode root = new TreeNode(A[n-1], 0);
16+
for (int i = n-1; i >= 0; i--) {
17+
res.addFirst(insert(root, A[i], 0));
18+
}
19+
return res;
20+
}
21+
22+
private int insert(TreeNode node, int val, int smallers) {
23+
if (node.val == val) return node.count + smallers;
24+
if (node.val < val) {
25+
if (node.right == null) {
26+
node.right = new TreeNode(val, 0);
27+
return node.count + smallers + 1;
28+
}
29+
return insert(node.right, val, node.count + smallers + 1);
30+
}
31+
32+
node.count++;
33+
if (node.left == null) {
34+
node.left = new TreeNode(val, 0);
35+
return smallers;
36+
}
37+
38+
return insert(node.left, val, smallers);
39+
}
40+
41+
class TreeNode {
42+
int val, count;
43+
TreeNode left, right;
44+
public TreeNode(int val, int count) {
45+
this.val = val;
46+
this.count = count;
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)