. ( ). [x, y], . ( solution ). , , ).
def min_with_none(a, b):
"""
Returns the minimum of two elements.
If one them is None, the other is returned.
"""
if a is None:
return b
if b is None
return a
return min(a, b)
def max_with_none(a, b):
"""
Returns the maximum of two elements.
If one them is None, the other is returned.
"""
if a is None:
return b
if b is None:
return a
return max(a, b)
def solution(x, y, T):
"""
This function returns a tuple
(max size of subtree in [x, y] range, total size of the subtree, min of subtree, max of subtree)
"""
if T is None:
return (0, 0, None, None)
left_ans, left_size, left_min, _ = solution(x, y, T.left)
right_ans, right_size, _, right_max = solution(x, y, T.right)
cur_size = 1 + left_size + right_size
cur_min = min_with_none(T.val, left_min)
cur_max = max_with_none(T.val, right_max)
cur_ans = max(left_ans, right_ans)
if x <= cur_min and cur_max <= y:
cur_ans = cur_size
return (cur_size, cur_ans, cur_min, cur_max)
, node node.