build之后不要忘记把当前Node和它的左右child连起来
/**
* 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) {
// write your code here
return build(A, 0, A.length - 1);
}
private SegmentTreeNode build(int[] A, int start, int end) {
if (start > end) return null;
if (start == end) return new SegmentTreeNode(start, end, A[start]);
int mid = (start + end) / 2;
SegmentTreeNode left = build(A, start, mid);
SegmentTreeNode right = build(A, mid + 1, end);
SegmentTreeNode res = new SegmentTreeNode(start, end, Math.max(left.max, right.max));
res.left = left;
res.right = right;
return res;
}
}
No comments:
Post a Comment