美文网首页
lintcode-线段树查询I

lintcode-线段树查询I

作者: 鬼谷神奇 | 来源:发表于2016-06-05 16:34 被阅读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);
            
        }
    };
    

    相关文章

      网友评论

          本文标题:lintcode-线段树查询I

          本文链接:https://www.haomeiwen.com/subject/xihrdttx.html