|
| 1 | +# 线段树的构造 II |
| 2 | + > 题目来源: [LintCode 算法题库](https://www.lintcode.com/problem/segment-tree-build-ii/?utm_source=sc-github-wzz) |
| 3 | + ## 题目描述 |
| 4 | + 线段树是一棵二叉树,他的每个节点包含了两个额外的属性`start`和`end`用于表示该节点所代表的区间。`start`和`end`都是整数,并按照如下的方式赋值: |
| 5 | + |
| 6 | + - 根节点的 `start` 和 `end` 由 `build` 方法所给出。 |
| 7 | + - 对于节点 A 的左儿子,有 `start=A.left, end=(A.left + A.right) / 2`。 |
| 8 | + - 对于节点 A 的右儿子,有 `start=(A.left + A.right) / 2 + 1, end=A.right`。 |
| 9 | + - 如果 `start` 等于 `end`, 那么该节点是叶子节点,不再有左右儿子。 |
| 10 | + |
| 11 | + 对于给定数组实现`build`方法, 线段树的每个节点储存区间最大值, 返回根节点. |
| 12 | + ### 样例说明 |
| 13 | + ``` |
| 14 | + 输入: [3,2,1,4] |
| 15 | + 解释: |
| 16 | + 这颗线段树将会是 |
| 17 | + [0,3](max=4) |
| 18 | + / \ |
| 19 | + [0,1] [2,3] |
| 20 | + (max=3) (max=4) |
| 21 | + / \ / \ |
| 22 | + [0,0] [1,1] [2,2] [3,3] |
| 23 | + (max=3)(max=2) (max=1)(max=4) |
| 24 | + ### 参考代码 |
| 25 | + 模板题, 递归构造线段树即可. 注意内存要分配在堆上, 而不是栈上. |
| 26 | +
|
| 27 | + Python代码为Python2版本 |
| 28 | + ```python |
| 29 | + """ |
| 30 | + Definition of SegmentTreeNode: |
| 31 | + class SegmentTreeNode: |
| 32 | + def __init__(self, start, end, max): |
| 33 | + self.start, self.end, self.max = start, end, max |
| 34 | + self.left, self.right = None, None |
| 35 | + """ |
| 36 | +
|
| 37 | + class Solution: |
| 38 | + # @oaram A: a list of integer |
| 39 | + # @return: The root of Segment Tree |
| 40 | + def build(self, A): |
| 41 | + return self.buildTree(0, len(A)-1, A) |
| 42 | +
|
| 43 | + def buildTree(self, start, end, A): |
| 44 | + if start > end: |
| 45 | + return None |
| 46 | +
|
| 47 | + node = SegmentTreeNode(start, end, A[start]) |
| 48 | + if start == end: |
| 49 | + return node |
| 50 | +
|
| 51 | + mid = (start + end) / 2 |
| 52 | + node.left = self.buildTree(start, mid, A) |
| 53 | + node.right = self.buildTree(mid + 1, end, A) |
| 54 | + if node.left is not None and node.left.max > node.max: |
| 55 | + node.max = node.left.max |
| 56 | + if node.right is not None and node.right.max > node.max: |
| 57 | + node.max = node.right.max |
| 58 | + return node |
| 59 | + ``` |
| 60 | + 更多题解请参考: [LintCode 提供 2000+ 算法题和名企阶梯训练](https://www.lintcode.com/problem/?utm_source=sc-github-wzz) |
| 61 | + |
0 commit comments