lintcode-线段树查询I

2016-06-05  本文已影响121人  鬼谷神奇
/**
 * Definition of SegmentTreeNode:
 * class SegmentTreeNode {
 * public:
 *     int start, end, max;
 *     SegmentTreeNode *left, *right;
 *     SegmentTreeNode(int start, int end, int max) {
 *         this->start = start;
 *         this->end = end;
 *         this->max = max;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
#define INF 0x7fffffff

class Solution {
public:
    /**
     *@param root, start, end: The root of segment tree and 
     *                         an segment / interval
     *@return: The maximum number in the interval [start, end]
     */
     
    int query(SegmentTreeNode *root, int start, int end) {
        // write your code here
        
        if(NULL == root) return -INF;
        if(root->start > end || root->end < start || start > end) {
            return -INF;
        }
        
        if(root->start >= start && root->end <= end) return root->max;
        
        int mid = (root->end + root->start)/2;
        int leftmax = query(root->left, start, min(mid, end));
        int rightmax = query(root->right, max(mid, start), end);
        return max(leftmax, rightmax);
        
    }
};
上一篇下一篇

猜你喜欢

热点阅读