我們可以遞歸地解決這個問題。我們需要知道每個子樹的左邊界和右邊界(即最小和最大的元素)。如果它位於範圍[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)
# Solves the problem for the children recursively
left_ans, left_size, left_min, _ = solution(x, y, T.left)
right_ans, right_size, _, right_max = solution(x, y, T.right)
# The size of this subtree
cur_size = 1 + left_size + right_size
# The left border of the subtree is T.val or the smallest element in the
# left subtree (if it's not empty)
cur_min = min_with_none(T.val, left_min)
# The right border of the subtree is T.val or the largest element in the
# right subtree (if it's not empty)
cur_max = max_with_none(T.val, right_max)
# The answer is the maximum of answer for the left and for the right
# subtree
cur_ans = max(left_ans, right_ans)
# If the current subtree is within the [x, y] range, it becomes the new answer,
# as any subtree of this subtree is smaller than itself
if x <= cur_min and cur_max <= y:
cur_ans = cur_size
return (cur_size, cur_ans, cur_min, cur_max)
該溶液顯然線性時間運行,因爲它訪問每一個節點僅一次,並執行每節點的操作的常數。