gpt4 book ai didi

algorithm - 查找范围内包含的 bst 的最大子树的大小

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:01:15 25 4
gpt4 key购买 nike

这是最近的一个面试问题。该问题要求找到包含在 [x, y] 范围内的 BST 的最大子树的大小。是x < y . BST 是递归定义的,其中每个节点都有一个整数值、一个左子节点和一个右子节点。我只能知道树中位于该范围内的节点总数,但无法找到最大的子树。这是我在 python 中使用的代码:

def solution(x, y, T):
if T is None:
return 0
size = 0
if x < T.val:
size += solution(x, y, T.left)
if x <= T.val and y >= T.val:
size += 1
# The following if statement was my attempt at resetting the count
# whenever we find a node outside the range, but it doesn't work
if x > T.val or y < T.val:
size = 0
if B > T.x:
size += solution(A, B, T.right)
return size

解决方案应该是O(N)其中 N是树中的节点数。

最佳答案

我们可以递归地解决这个问题。我们需要知道每个子树的左右边界(即最小和最大的元素)。如果它位于 [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)

这个解决方案显然以线性时间运行,因为它只访问每个节点一次,并且每个节点执行恒定数量的操作。

关于algorithm - 查找范围内包含的 bst 的最大子树的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com