class SegmentTree(object):
def __init__(self, nums, s=None, e=None):
"""
initialize your data structure here.
:type nums: List[int]
"""
n = len(nums)
if s == None:
self.start, self.end = 0, n-1
else:
self.start, self.end = s, e
self.mid = self.start + (self.end-self.start)/2
self.left, self.right = None, None
self.val = 0
if self.end < self.start:
return
if self.end == self.start:
self.val = nums[self.start]
else:
self.left = SegmentTree(nums, self.start, self.mid)
self.right = SegmentTree(nums, self.mid+1, self.end)
self.val = self.left.val + self.right.val
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: int
"""
if i == self.start and i == self.end:
self.val = val
else:
if i <= self.mid:
self.left.update(i, val)
else:
self.right.update(i, val)
self.val = self.left.val + self.right.val
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
if i == self.start and j == self.end:
return self.val
elif self.start > j or self.end < i:
return 0
else:
if i > self.mid:
return self.right.sumRange(i, j)
elif j <= self.mid:
return self.left.sumRange(i, j)
else:
return self.left.sumRange(i, self.mid) + self.right.sumRange(self.mid+1, j)