lintcode:线段树的查询

线段树的查询

对于一个有n个数的整数数组,在对应的线段树中, 根节点所代表的区间为0-n-1, 每个节点有一个额外的属性max,值为该节点所代表的数组区间start到end内的最大值。

为SegmentTree设计一个 query 的方法,接受3个参数rootstartend,线段树root所代表的数组中子区间[start, end]内的最大值。

解题

递归

/**
 * 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 root, start, end: The root of segment tree and 
     *                         an segment / interval
     *@return: The maximum number in the interval [start, end]
     */
    public int query(SegmentTreeNode root, int start, int end) {
        // write your code here
        if(null == root) return Integer.MIN_VALUE;
        if(root.start > end || root.end < start || start > end) return Integer.MIN_VALUE;
        if(root.start >= start && root.end <= end) return root.max;

        int mid = root.start + (root.end - root.start)/2;
        int leftmax = query(root.left, start, Math.min(mid, end));
        int rightmax = query(root.right, Math.max(mid, start), end);
        return Math.max(leftmax, rightmax);
    }
}
Java Code
原文地址:https://www.cnblogs.com/bbbblog/p/5284821.html