Segment Tree Query(线段树的查询)

http://www.lintcode.com/zh-cn/problem/segment-tree-query/
请先参阅 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 root: The root of segment tree.
     * @param start: start value.
     * @param end: end value.
     * @return: The maximum number in the interval [start, end]
     */
    public int query(SegmentTreeNode root, int start, int end) {
        // write your code here
        
        if (root.start == start && root.end == end) {
            return root.max;
        }
        int mid = (root.start + root.end) >>> 1;
        if (end <= mid) {
            
            return query(root.left, start, end);
        } else if (start >= mid + 1) {
            
            return query(root.right, start, end);
        } else {
            
            return Math.max(query(root.left, start, mid), query(root.right, mid + 1, end));
        }
    }
}

你可能感兴趣的:(Segment Tree Query(线段树的查询))