Lintcode201 Segment Tree Build solution 题解

【题目描述】

 

 

The structure of Segment Tree is a binary tree which each node has two attributes start and end denote an segment / interval.

start and end are both integers, they should be assigned in following rules:

The root's start and end is given by build method.

The left child of node A has start=A.left, end=(A.left + A.right) / 2.

The right child of node A has start=(A.left + A.right) / 2 + 1, end=A.right.

if start equals to end, there will be no children for this node.

Implement a build method with two parameters start and end, so that we can create a corresponding segment tree with every node has the correct start and end value, return the root of this segment tree.

线段树是一棵二叉树,他的每个节点包含了两个额外的属性start和end用于表示该节点所代表的区间。start和end都是整数,并按照如下的方式赋值:

根节点的startend由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方法,接受startend作为参数, 然后构造一个代表区间[start, end]的线段树,返回这棵线段树的根。

【题目链接】

www.lintcode.com/en/problem/segment-tree-build/

【题目解析】

这是数据结构的题目: 通过分析需要什么操作来找到适合的数据结构进行使用。

线段树:区间操作就一定要想到线段树

 1.区间Get max/min, sum, count 

2.线段树的三个性质(I. 这个是一个二叉树, II. 每个节点表示一段区间的max 或者sum。 III. 非叶子节点: 左右儿子等于叶子区间平分后的左右区间, 值等于左 右儿子的值的更新。)

 3.了解线段树三个接口build, query, modify.

【参考答案】

www.jiuzhang.com/solutions/segment-tree-build/

 

posted @ 2018-02-06 23:47  admondguo  阅读(89)  评论(0编辑  收藏  举报