-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount of Range Sum BST
81 lines (76 loc) · 2.48 KB
/
Count of Range Sum BST
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/////
http://www.qinshaoxuan.com/articles/930.html
public class Solution {
private class TreeNode {
long val = 0;
int count = 1;
int leftSize = 0;
int rightSize = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(long v) {
this.val = v;
this.count = 1;
this.leftSize = 0;
this.rightSize = 0;
}
}
private TreeNode insert(TreeNode root, long val) {
if(root == null) {
return new TreeNode(val);
} else if(root.val == val) {
root.count++;
} else if(val < root.val) {
root.leftSize++;
root.left = insert(root.left, val);
} else if(val > root.val) {
root.rightSize++;
root.right = insert(root.right, val);
}
return root;
}
private int countSmaller(TreeNode root, long val) {
if(root == null) {
return 0;
} else if(root.val == val) {
return root.leftSize;
} else if(root.val > val) {
return countSmaller(root.left, val);
} else {
return root.leftSize + root.count + countSmaller(root.right, val);
}
}
private int countLarger(TreeNode root, long val) {
if(root == null) {
return 0;
} else if(root.val == val) {
return root.rightSize;
} else if(root.val < val) {
return countLarger(root.right, val);
} else {
return countLarger(root.left, val) + root.count + root.rightSize;
}
}
private int rangeSize(TreeNode root, long lower, long upper) {
int total = root.count + root.leftSize + root.rightSize;
int smaller = countSmaller(root, lower); // Exclude everything smaller than lower
int larger = countLarger(root, upper); // Exclude everything larger than upper
return total - smaller - larger;
}
public int countRangeSum(int[] nums, int lower, int upper) {
if(nums.length == 0) {
return 0;
}
long[] sums = new long[nums.length + 1];
for(int i = 0; i < nums.length; i++) {
sums[i + 1] = sums[i] + nums[i];
}
TreeNode root = new TreeNode(sums[0]);
int output = 0;
for(int i = 1; i < sums.length; i++) {
output += rangeSize(root, sums[i] - upper, sums[i] - lower);
insert(root, sums[i]);
}
return output;
}
}