线段树——入门学习(java代码实现)

Posted 小乖乖的臭坏坏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线段树——入门学习(java代码实现)相关的知识,希望对你有一定的参考价值。

SegmentTree.java

public class SegmentTree 
    int[] arr, tree;

    public SegmentTree(int[] arr, int[] tree) 
        this.arr = arr;
        this.tree = tree;
        build_tree(0, 0, arr.length-1);
    

    public void build_tree(int node, int start, int end)
        if(start==end)
            tree[node] = arr[start];
        
        else 
            int mid = (start + end) / 2;
            int left_node = 2*node+1;
            int right_node = 2*node+2;

            build_tree(left_node, start, mid);
            build_tree(right_node, mid+1, end);
            tree[node] = tree[left_node]+tree[right_node];

        

    
    public int query_tree(int node, int start, int end, int L, int R)
        if(R<start || L>end)return 0;
        else if(L<=start && end<=R)
            return tree[node];
        
//        else if(start==end)return tree[node];
        else 
            int mid = (start+end) / 2;
            int left_node = 2 * node +1;
            int right_node = 2 * node + 2;
            int sum_left = query_tree(left_node, start ,mid, L, R);
            int sum_right = query_tree(right_node, mid+1 ,end, L, R);
            return sum_left+sum_right;
        
    
    public void update_tree(int node, int start, int end, int idx, int val)
        if(start==end)
            arr[idx] = val;
            tree[node] = val;
        
        else 
            int mid = (start+end) / 2;
            int left_node = 2 * node +1;
            int right_node = 2 * node + 2;
            if (idx >= start &&idx <=mid)
                update_tree(left_node, start, mid, idx, val);
            
            else 
                update_tree(right_node, mid+1, end, idx, val);
            
            tree[node] = tree[left_node] + tree[right_node];
        
    


SegmentTreeDemo.java

public class SegmentTreeDemo 
    public static void main(String[] args) 
        int arr[] = 1,3,5,7,9,11;
        int size = 6;
        int tree[] = new int[100];

        SegmentTree st = new SegmentTree(arr, tree);

        st.build_tree(0, 0, size-1);

        for (int i:tree)
            System.out.print(i+" ");
        

        System.out.println();

        st.update_tree(0, 0, size-1, 4, 6);

        for (int i:tree)
            System.out.print(i+" ");
        

        System.out.println();

        System.out.println(st.query_tree(0, 0, size-1, 2, 5));

    


输出:

36 9 27 4 5 16 11 1 3 0 0 7 9 0 0
33 9 24 4 5 13 11 1 3 0 0 7 6 0 0
29

以上是关于线段树——入门学习(java代码实现)的主要内容,如果未能解决你的问题,请参考以下文章

线段树——入门学习(java代码实现)

字典树——入门学习(java代码实现)

字典树——入门学习(java代码实现)

主席树学习--入门

线段树基础

线段树入门