七. Segment Tree 1 Segment Tree Build


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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容