线段树(区间树)

一、简介
线段树,类似区间树,它在各个节点保存一条线段(数组中的一段子数组),主要用于高效解决连续区间的动态查询问题,由于二叉结构的特性,它基本能保持每个操作的复杂度为O(logn)。
线段树的每个节点表示一个区间,子节点则分别表示父节点的左右半区间,例如父亲的区间是[a,b],那么(c=(a+b)/2)左儿子的区间是[a,c],右儿子的区间是[c+1,b]。
二、举例
例1:给一个数组array[1,…,n],求出下标i,j之间的和
例2:给一个数组array[1,…,n],求出下标i,j之间最小值
nums = {1,3,5}
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
线段树(区间树)_第1张图片

public class NumArray {
  class TreeNode
{
    int start, end;
    int val;
    TreeNode left,right;
    public TreeNode(int s,int e,int v) {
        // TODO Auto-generated constructor stub
        this.start = s;
        this.end = e;
        this.val = v;
    }
}
    TreeNode segmentTree;
        int[] nums;
        public NumArray(int[] nums) {
            this.nums = nums;
            int sum = 0;
            for(int num : nums){sum += num;}
            segmentTree = treeConstruct(0, nums.length-1,sum);
        }

        private TreeNode treeConstruct(int s, int e, int sum) {
            // TODO Auto-generated method stub
            if(e - s < 1){return null;}
            //if(e - s == 1)return new TreeNode(s, e, sum);
            TreeNode tree = new TreeNode(s, e, sum);
            int mid = (s + e) >> 1;
            int val = 0;
            for(int i = s;i<=mid;i++){val += nums[i];}
            tree.left = treeConstruct(s, mid, val);
            tree.right = treeConstruct(mid+1, e, sum - val);
            return tree;
        }

        public void update(int i, int val) {
            helper(i, val, segmentTree);
            nums[i] = val;
        }
        void helper(int i, int val, TreeNode tree)
        {
            if(tree == null) return;
            tree.val = tree.val - nums[i] + val;
            int mid = (tree.start + tree.end) >> 1;
            if(i <= mid)
            {
                helper(i, val, tree.left);
            }else
                helper(i, val, tree.right);

        }
        public int sumRange(int i, int j) {
           return getSum(i, j, segmentTree);

        }
        int getSum(int i,int j,TreeNode tree)
        {
            if(i > j) return 0 ;
             if(i == j) return nums[i];
             if(i == tree.start && j == tree.end) return tree.val;
             int mid = (tree.start+tree.end)>>1;
             if(i <= mid && j >= mid)
             {
                 return getSum(i, mid, tree.left) + getSum(mid+1, j, tree.right);
             }
             if(i <= mid && j <= mid)
             {
                 return getSum(i, j, tree.left);
             }

             if(i >= mid && j >=mid)
             {
                 return getSum(i, j, tree.right);
             }
             return 0;

        }
}


// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);

你可能感兴趣的:(数据结构)