这个写法好像是错的!
第一遍写的时候一直报null pointer exception
问题是这个query的区间有可能是超越tree的区间的
只要还有Overlap就合法
但是不能保证正好满足边界
所以对于base case来说只要 root.start == root.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, start, end: The root of segment tree and
* an segment / interval
*@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 || start > end || start > root.end || end < root.start) return 0;
if (start == root.start && end == root.end || root.start == root.end) return root.count;
int mid = (root.start + root.end) / 2;
if (end <= mid) return query(root.left, start, end);
else if (start > mid) return query(root.right, start, end);
else {
return query(root.left, start, mid) + query(root.right, mid + 1, end);
}
}
}
No comments:
Post a Comment