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;
}
*/
}
本文介绍了一种针对段树查询操作的优化方法,特别是在查询区间超出原区间范围时的处理方式。通过调整查询区间并递归地查找左子树和右子树,确保返回正确的计数结果。
3万+

被折叠的 条评论
为什么被折叠?



