七. Segment Tree 2 Segment Tree Query


Idea:
It is considerable that 4 situations should be included:

  1. start, end are all equal to range of node
  2. start, end is in the range of node.left
  3. start, end is in the range of node.right
  4. start is on the range of node.left but end is in the range of node.right.

Therefore, the recursion should be in this way.

"""
Definition of SegmentTreeNode:
class SegmentTreeNode:
    def __init__(self, start, end, max):
        self.start, self.end, self.max = start, end, max
        self.left, self.right = None, None
"""

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]
    """
    def query(self, root, start, end):
        # write your code here
       #  start, end are all equal to range of node
        if start == root.start and end == root.end:
            return root.max

        # start, end is in the range of node.left
        if root.left.end < start:
            max = self.query(root.right, start, end)
            return max
        else:
            # start, end is in the range of node.right
            if root.right.start > end:
                max = self.query(root.left, start, end)
                return max
            else:
                # start is on the range of node.left 
                #but end is in the range of node.right.
                max_1 = self.query(root.left, start, root.left.end)
                
                max_2 = self.query(root.right, root.right.start, end)
                
                if max_1 < max_2:
                    return max_2
                else: 
                    return max_1
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容