Segment Tree / Binary Indexed Tree

The structure of Segment Tree is a binary tree which each node has two attributesstartandenddenote an segment / interval.

_start _and _end _are both integers, they should be assigned in following rules:

  • The root's _start _and _end _is given by buildmethod.

  • The left child of node A has start=A.left, end=(A.left + A.right) / 2.

  • The right child of node A has start=(A.left + A.right) / 2 + 1, end=A.right.

  • if start _equals to _end, there will be no children for this node.

Implement a buildmethod with a given array, so that we can create a corresponding segment tree with every node value represent the corresponding interval max value in the array, return the root of this segment tree.

Build:

/**
 * 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 buildHelper(0, A.length -1, A);
    }

    public SegmentTreeNode buildHelper(int start, int end, int[] A ){
        if(start > end){
            return null;
        }
        if (start == end){
            return new SegmentTreeNode (start, end, A[start]);
        }

        SegmentTreeNode left = buildHelper(start, (start + end) / 2, A);
        SegmentTreeNode right = buildHelper((start + end) / 2 + 1, end, A);

        SegmentTreeNode ret = new SegmentTreeNode(start, end, Math.max(left.max, right.max));
        ret.left = left;
        ret.right = right;
        return ret;

    }
}

Query:

Modify:

Last updated

Was this helpful?