您的位置:首页 > 其它

247 - 线段树查询 II

2017-09-08 14:13 232 查看
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;
}
*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: