线段树查询 II
2015-10-29 00:57
344 查看
对于一个数组,我们可以对其建立一棵
实现一个
样例
对于数组
线段树, 每个结点存储一个额外的值
count来代表这个结点所指代的数组区间内的元素个数. (数组中并不一定每个位置上都有元素)
实现一个
query的方法,该方法接受三个参数
root,
start和
end, 分别代表线段树的根节点和需要查询的区间,找到数组中在区间[start, end]内的元素个数。
样例
对于数组
[0, 空,2, 3], 对应的线段树为:
[0, 3, count=3] / \ [0,1,count=1] [2,3,count=2] / \ / \ [0,0,count=1] [1,1,count=0] [2,2,count=1], [3,3,count=1]
query(1, 1), return
0
query(1, 2), return
1
query(2, 3), return
2
query(0, 2), return
2
/** * Definition of SegmentTreeNode: * class SegmentTreeNode { * public: * int start, end, count; * SegmentTreeNode *left, *right; * SegmentTreeNode(int start, int end, int count) { * this->start = start; * this->end = end; * this->count = count; * this->left = this->right = NULL; * } * } */ class Solution { public: /** *@param root, start, end: The root of segment tree and * an segment / interval *@return: The count number in the interval [start, end] */ int query(SegmentTreeNode *root, int start, int end) { // write your code here if (root == NULL || start > root->end) { return 0; } if (start == root->start && end == root->end) { return root->count; } else if (start >= root->left->start && start <= root->left->end) { if (end <= root->left->end) { return query(root->left, start, end); } else { return query(root->left, start, root->left->end) + query(root->right, root->right->start, min(end, root->right->end)); } } else { return query(root->right, start, min(end, root->right->end)); } } };
相关文章推荐
- HDU 2859 Phalanx
- 给信息安全专业学生的书单
- spark学习系列
- OC内存管理一
- Python Django安装
- django sqlite3迁移到mysql
- Eclipse将引用了第三方jar包的Java项目打包成jar文件的两种方法
- 数据库中表散列
- OC基础第五章:构造方法
- 【Java】获取泛型的类型
- android 群英传读书笔记---listview使用技巧(一)
- 怎样删除虚拟机快照
- Java记录 -47- 线性数据结构
- 1.为什么需要用到模板引擎
- loading Bar
- JS模板引擎 :ArtTemplate
- ListActivity 的使用和在 ListView中添加图片文字
- sql按照首字符分组
- Java NIO入门
- iOS输入框UITextView随键盘UIkeyboard弹出与消失改变Rect