线段树的构造 II-LintCode
来源:互联网 发布:python查找txt内容 编辑:程序博客网 时间:2024/06/08 07:33
线段树是一棵二叉树,他的每个节点包含了两个额外的属性start和end用于表示该节点所代表的区间。start和end都是整数,并按照如下的方式赋值:
- 根节点的 start 和 end 由 build 方法所给出。
- 对于节点 A 的左儿子,有 start=A.left, end=(A.left + A.right) / 2。
- 对于节点 A 的右儿子,有 start=(A.left + A.right) / 2 + 1, end=A.right。
- 如果 start 等于 end, 那么该节点是叶子节点,不再有左右儿子。
对于给定数组设计一个build方法,构造出线段树
样例:
给出[3,2,1,4],线段树将被这样构造
[0, 3] (max = 4) / \ [0, 1] (max = 3) [2, 3] (max = 4) / \ / \[0, 0](max = 3) [1, 1](max = 2)[2, 2](max = 1) [3, 3] (max = 4)
#ifndef C439_H#define C439_H#include<iostream>#include<vector>using namespace std;class SegmentTreeNode{public: int start, end, max; SegmentTreeNode *left, *right; SegmentTreeNode(int start, int end, int max) { this->start = start; this->end = end; this->max = max; this->left = this->right = NULL; }};class Solution {public: /* * @param A: a list of integer * @return: The root of Segment Tree */ SegmentTreeNode * build(vector<int> &A) { // write your code here int len = A.size(); SegmentTreeNode *root = buildRecur(A, 0, len - 1); return root; } SegmentTreeNode* buildRecur(vector<int> &A, int i, int j) { if (i > j) return NULL; else if (i == j) { SegmentTreeNode *node = new SegmentTreeNode(i, i, A[i]); return node; } else { SegmentTreeNode *node = new SegmentTreeNode(i, j, 0); node->left = buildRecur(A, node->start, (node->start + node->end) / 2); node->right = buildRecur(A, (node->start + node->end) / 2 + 1, node->end); node->max = maxVal(node->left->max, node->right->max); return node; } } int maxVal(int a, int b) { return a > b ? a : b; }};#endif
阅读全文
0 0
- LintCode:线段树的构造 II
- 线段树的构造 II-LintCode
- LintCode:线段树的构造
- lintcode -- 线段树的构造
- 线段树的构造-LintCode
- LintCode:线段树的查询II
- 线段树的构造 II
- lintcode-线段树的构造-201
- 线段树查询 II-LintCode
- lintcode segment-tree-build 线段树的构造
- lintcode-线段树查询II-247
- lintcode(247)线段树查询 II
- LintCode:线段树的查询
- LintCode:线段树的修改
- lintcode线段树的应用
- 线段树的查询-LintCode
- 线段树的修改-LintCode
- [LintCode]Segment Tree Build 构造线段树
- java 简单练习
- 《由浅到深使用回调函数 2》(快速排序)
- 大数据学习要知道的十大发展趋势,以及学习大数据的几点建议
- 比特币老兵之续集
- 第五周项目3--括号的匹配
- 线段树的构造 II-LintCode
- 异常----自定义异常
- 开坑
- bzoj 2762: [JLOI2011]不等式组 树状数组
- Java开发中的23种设计模式详解(转)
- 鼠标事件被禁用了
- 第七周项目二
- 第八周项目一 顺序串算法库
- 设置小米5手机拒接中介骚扰标志的电话