Interval Sum II(区间求和 II)

http://www.lintcode.com/en/problem/interval-sum-ii/
请参阅
Segment Tree Build II(线段树的构造 II)
Segment Tree Query II(线段树查询 II)
Segment Tree Modify(线段树的修改)

public class Solution {
    /* you may need to use some attributes here */
    private Node root;

    /*
    * @param A: An integer array
    */
    public Solution(int[] A) {
        // do intialization if necessary
        root = build(A, 0, A.length - 1);
    }

    /*
     * @param start: An integer
     * @param end: An integer
     * @return: The sum from start to end
     */
    public long query(int start, int end) {
        // write your code here
        if (root == null) {
            return 0;
        }
        return query(root, start, end);
    }

    private Long query(Node root, int start, int end) {
        if (root.start == start && root.end == end) {
            return root.sum;
        }
        int mid = (root.start + root.end) >>> 1;
        if (start >= mid + 1) {
            return query(root.right, start, end);
        } else if (end <= mid) {
            return query(root.left, start, end);
        } else {
            return query(root.left, start, mid) + query(root.right, mid + 1, end);
        }
    }

    /*
     * @param index: An integer
     * @param value: An integer
     * @return: nothing
     */
    public void modify(int index, int value) {
        if (root == null) {
            return;
        }
        // write your code here
        modify(root, index, value);
    }

    private void modify(Node root, int index, int value) {
        // write your code here
        if (index == root.start && index == root.end) {
            root.sum = value;
            return;
        }
        int mid = (root.start + root.end) >>> 1;
        if (index <= mid) {
            modify(root.left, index, value);
        } else {
            modify(root.right, index, value);
        }
        root.sum = root.left.sum + root.right.sum;
    }

    private Node build(int[] a, int l, int r) {
        if (a.length==0){
            return null;
        }
        Node node = new Node(l, r, a[l]);
        if (l == r) {
            return node;
        }
        int mid = (l + r) >>> 1;
        node.left = build(a, l, mid);
        node.right = build(a, mid + 1, r);
        node.sum = node.left.sum + node.right.sum;
        return node;
    }

    private class Node {
        int start, end;
        long sum;
        Node left, right;

        public Node(int start, int end, long sum) {
            this.start = start;
            this.end = end;
            this.sum = sum;
        }
    }
}

你可能感兴趣的:(Interval Sum II(区间求和 II))