手敲数据结构——线段树

主要用来出来区间计算问题

public interface Merger {
    E merger(E a, E b);
}

public class SegmentTree {

    private E[] tree;
    private E[] data;
    private Merger merger;

    //创建数组的大小  如果数组的长度正好为 2^n 此时 tree的长度2n就可以了 但是在数组的长度大于2^n的情况下 tree的长度就应该为4n了
    public SegmentTree(E[] arr, Merger merger) {
        this.merger = merger;

        data = (E[]) arr;

        tree = (E[]) new Object[4 * arr.length];
        buildSegmentTree(0, 0, data.length - 1);
    }

    // 在treeIndex的位置创建表示区间[l...r]的线段树
    private void buildSegmentTree(int treeIndex, int l, int r) {
        if (l == r) {
            tree[treeIndex] = data[l];
            return;
        }
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        //计算中间节点
        int middle = l + (r - l) / 2;
        buildSegmentTree(leftTreeIndex, l, middle);
        buildSegmentTree(rightTreeIndex, middle + 1, r);
        // 通过子节点计算 当前节点
        tree[treeIndex] = merger.merger(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    public int getSize() {
        return data.length;
    }

    public E get(int index) {
        if (index < 0 || index >= data.length) throw new IllegalArgumentException("index is illegal ");
        return data[index];
    }

    //返回完全二叉树的数组表示中,一个索引所表示的元素的左孩子节点的索引
    private int leftChild(int index) {
        return index * 2 + 1;
    }

    // 返回完全二叉树的数组表示中,一个索引所表示的元素的右孩子节点的索引
    private int rightChild(int index) {
        return index * 2 + 2;
    }

    // 返回区间[queryL, queryR]的值
    public E query(int queryL, int queryR) {

        if (queryL < 0 || queryL >= data.length ||
                queryR < 0 || queryR >= data.length || queryL > queryR)
            throw new IllegalArgumentException("Index is illegal.");

        return query(0, 0, data.length - 1, queryL, queryR);
    }

    // 在以treeIndex为根的线段树中[l...r]的范围里,搜索区间[queryL...queryR]的值
    private E query(int treeIndex, int l, int r, int queryL, int queryR) {
        if (l == queryL && r == queryR) {
            return tree[treeIndex];
        }
        int middle = l + (r - l) / 2;
        // treeIndex的节点分为[l...mid]和[mid+1...r]两部分

        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        //查询的结果全部在 左边 或者 右边 的情况
        if (queryL >= middle + 1) {
            return query(rightTreeIndex, middle + 1, r, queryL, queryR);
        } else if (queryR <= middle) {
            return query(leftTreeIndex, l, middle, queryL, queryR);
        }
        //查询的结果在 左边和右边 都有的情况
        E lr = query(leftTreeIndex, l, middle, queryL, middle);
        E rr = query(rightTreeIndex, middle + 1, r, middle + 1, queryR);
        return merger.merger(lr, rr);
    }

    public void set(int index, E e) {
        if (index < 0 || index >= data.length)
            throw new IllegalArgumentException("Index is illegal.");
        data[index] = e;
        set(0, 0, data.length - 1, index, e);
    }

    // 在以treeIndex为根的线段树中更新index的值为e
    private void set(int treeIndex, int l, int r, int index, E e) {
        if (l == r) {
            tree[treeIndex] = e;
            return;
        }
        int middle = l + (r - l) / 2;
        // treeIndex的节点分为[l...mid]和[mid+1...r]两部分
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);

        if (index >= middle + 1) {
            set(rightTreeIndex, middle + 1, r, index, e);
        } else {
            set(leftTreeIndex, l, middle, index, e);
        }
        //内容变了 重新赋值
        tree[treeIndex] = merger.merger(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < tree.length; i++) {
            if (tree[i] != null) {
                sb.append(tree[i]);
            } else {
                sb.append("null");
            }
            if (i != tree.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

测试:

public class Main {

    public static void main(String[] args) {

        Integer[] nums = {-2, 0, 3, -5, 2, -1};
        SegmentTree segTree = new SegmentTree<>(nums,
                (a, b) -> a + b);
        System.out.println(segTree);

        System.out.println(segTree.query(0,2));
        System.out.println(segTree.query(2,5));
        System.out.println(segTree.query(0,5));
    }
}

输出

[-3,1,-4,-2,3,-3,-1,-2,0,null,null,-5,2,null,null,null,null,null,null,null,null,null,null,null]
1
-1
-3

你可能感兴趣的:(手敲数据结构——线段树)