美文网首页
七. Segment Tree 1 Segment Tree B

七. Segment Tree 1 Segment Tree B

作者: 何大炮 | 来源:发表于2018-03-16 09:59 被阅读0次

    Idea:
    The recursion is required here for every node has two children. (if here is only one child, while loop could be used.)

    """
    Definition of SegmentTreeNode:
    class SegmentTreeNode:
        def __init__(self, start, end):
            self.start, self.end = start, end
            self.left, self.right = None, None
    """
    
    
    class Solution:
        """
        @param: start: start value.
        @param: end: end value.
        @return: The root of Segment Tree.
        """
        def build(self, start, end):
            # write your code here
            if start > end:
                return None
                
            head = SegmentTreeNode(start, end)
            if start == end:
                return head
            
            def sub_build(node, start, end):
                
                start_1 = start
                end_1 = int((start + end)/2)
                node_left = SegmentTreeNode(start_1, end_1)
                node.left = node_left
                if start_1 != end_1:
                    sub_build(node_left, start_1, end_1)
                
                start_2 = int((start + end)/2 + 1)
                end_2 = end
                node_right = SegmentTreeNode(start_2, end_2)
                node.right = node_right
                if start_2 != end_2:
                    sub_build(node_right, start_2, end_2)
                
                return None
                
            sub_build(head, start, end)
            
            return head
    

    相关文章

      网友评论

          本文标题:七. Segment Tree 1 Segment Tree B

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