2017.9.8
注意处理一下,当给定的区间超出原区间范围时的情况。
也就是这里的这种情况。剩下的就没有什么问题了。
if(start < sNode.start){
start = sNode.start;
}
if(end > sNode.end){
end = sNode.end;
}
/**
* Definition of SegmentTreeNode:
* public class SegmentTreeNode {
* public int start, end, count;
* public SegmentTreeNode left, right;
* public SegmentTreeNode(int start, int end, int count) {
* this.start = start;
* this.end = end;
* this.count = count;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of segment tree.
* @param start: start value.
* @param end: end value.
* @return: The count number in the interval [start, end]
*/
public int query(SegmentTreeNode root, int start, int end) {
// write your code here
if(root == null || root.count == 0){
return 0;
}
int count = 0;
SegmentTreeNode sNode = root;
int mid = (sNode.end + sNode.start)/2;
if(start < sNode.start){
start = sNode.start;
}
if(end > sNode.end){
end = sNode.end;
}
if(start == sNode.start && end == sNode.end){
return count + sNode.count;
}
if(end <= mid){
return count + query(sNode.left,start,end);
}
if(start > mid){
return count + query(sNode.right,start,end);
}
else{
return count + query(sNode.left,start,mid) + query(sNode.right,mid + 1, end);
}
}
/*
public int query(SegmentTreeNode root, int start, int end) {
int count = 0;
count = query(root,start,end,count);
return count;
}
*/
}