【发布时间】:2021-01-11 22:24:50
【问题描述】:
我现在正在寻找总和最大的从根到叶的路径。我的做法是:
def max_sum(root):
_max = 0
find_max(root, _max, 0)
return _max
def find_max(node, max_sum, current_sum):
if not node:
return 0
current_sum += node.value
if not node.left and not node.right:
print(current_sum, max_sum, current_sum > max_sum)
max_sum = max(max_sum, current_sum)
if node.left:
find_max(node.left, max_sum, current_sum)
if node.right:
find_max(node.right, max_sum, current_sum)
current_sum -= node.value
class TreeNode():
def __init__(self, _value):
self.value = _value
self.left, self.right, self.next = None, None, None
def main():
root = TreeNode(1)
root.left = TreeNode(7)
root.right = TreeNode(9)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(2)
root.right.right = TreeNode(7)
print(max_sum(root))
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(4)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print(max_sum(root))
main()
有输出:
12 0 True
13 0 True
12 0 True
17 0 True
0
23 0 True
23 0 True
18 0 True
0
Process finished with exit code 0
预期的输出是 17 和 23。
我想确认一下为什么我的方法无法比较max_sum 和current_sum?即使它在比较中返回 true,但不会更新 max_sum。感谢您的帮助。
【问题讨论】:
-
没有详细查看您的代码,但是拥有一个函数和另一个同名变量是个坏主意
-
在
max_sum中,_max被设置为 0,然后从不改变。因此,返回 0。 -
谢谢,@turtle。我不确定哪个变量名与函数名冲突?
-
谢谢@mkrieger1。你介意解释更多吗?我虽然我的代码将更新
find_max函数中的_max。 -
@QiangSuper:我的意思是
max_sum。同样正如其他人指出的那样,问题在于max_sum内部的变量find_max仅对该函数是本地的。更新它的值不会改变_max的值