【发布时间】:2020-12-11 05:05:15
【问题描述】:
问题:给定一棵通用树和一个整数 n。在树中查找并返回具有下一个较大元素的节点,即找到一个值刚好大于 n 的节点。
虽然我能够通过删除后面的 for 循环并在调用递归时进行比较来解决它是 O(n)。我有点好奇以下代码版本的时间复杂度。
我提出了递归关系为 T(n) = T(n-1) + (n-1) = O(n^2)。其中 T(n-1) 是孩子们花费的时间,+ (n-1) 是为了找到下一个更大的(第二个 for 循环)。我做对了吗?还是我错过了什么?
def nextLargestHelper(root, n):
"""
root => reference to root node
n => integer
Returns node and value of node which is just larger not first larger than n.
"""
# Special case
if root is None:
return None, None
# list to store all values > n
largers = list()
# Induction step
if root.data > n:
largers.append([root, root.data])
# Induction step and Base case; if no children do not call recursion
for child in root.children:
# Induction hypothesis; my function returns me node and value just larger than 'n'
node, value = nextLargestHelper(child, n)
# If larger found in subtree
if node:
largers.append([node, value])
# Initialize node to none, and value as +infinity
node = None
value = sys.maxsize
# travers through all larger values and return the smallest value greater than n
for item in largers: # structure if item is [Node, value]
# this is why value is initialized to +infinity; so as it is true for first time
if item[1] < value:
node = item[0]
value = item[1]
return node, value
【问题讨论】:
标签: python algorithm recurrence