【发布时间】:2019-05-13 01:17:05
【问题描述】:
在网上找到了这段代码,它可以用来在树中找到两个叶子节点之间的最大值:
INT_MIN = -2**32
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxPathSumUtil(root, res):
if root is None:
return 0
if root.left is None and root.right is None:
return root.data
ls = maxPathSumUtil(root.left, res)
rs = maxPathSumUtil(root.right, res)
# If both left and right children exist
if root.left is not None and root.right is not None:
res[0] = max(res[0], ls + rs + root.data)
return max(ls, rs) + root.data
# If any of the two children is empty, return
# root sum for root being on one side
if root.left is None:
return rs + root.data
else:
return ls + root.data
def maxPathSum(root):
res = [INT_MIN]
maxPathSumUtil(root, res)
return res[0]
我的问题是关于res[0]。为什么要使用只有一个值的列表来跟踪该节点的最大值?我尝试将其更改为常规整数,但没有正确更新。它返回错误的值。那么为什么在递归函数期间使用具有单个值的列表而不是使用常规整数来跟踪最大值呢?
【问题讨论】:
-
当您分配给
res时,您重新分配它以引用不同的对象。通过传递list,您可以改为修改列表。如果您将res重新分配到新列表,它也将不起作用。