线段树是一棵二叉树,他的每个节点包含了两个额外的属性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方法,构造出线段树
wiki: Segment Tree Interval Tree
给出[3,2,1,4],线段树将被这样构造
递归构造线段树,max值得获取参看202.Segment Tree Query-线段树的查询(中等题)
/** * Definition of SegmentTreeNode: * public class SegmentTreeNode { * public int start, end, max; * public SegmentTreeNode left, right; * public SegmentTreeNode(int start, int end, int max) { * this.start = start; * this.end = end; * this.max = max * this.left = this.right = null; * } * } */ public class Solution { /** *@param A: a list of integer *@return: The root of Segment Tree */ public SegmentTreeNode build(int[] A) { if (A.length == 0) { return null; } SegmentTreeNode root = new SegmentTreeNode(0,A.length-1,0); create(A,root); return root; } private int create(int[] A, SegmentTreeNode root) { if (root.start == root.end) { root.max = A[root.start]; return root.max; } root.left = new SegmentTreeNode(root.start,(root.start+root.end)/2,0); root.right = new SegmentTreeNode((root.start+root.end)/2+1,root.end,0); root.max = Math.max(create(A,root.left),create(A,root.right)); return root.max; } }Last Update 2016.11.18