【问题标题】:How is the value returned from the function SumOfLongRootToLeafPathSumOfLongRootToLeafPath 函数返回的值如何
【发布时间】:2023-11-10 07:37:01
【问题描述】:

我正在解决二叉树的一些问题,但我陷入了这个问题https://www.geeksforgeeks.org/sum-nodes-longest-path-root-leaf-node/ 我正在使用 python 来解决这个问题 我理解链接上给出的解决方案的逻辑,但我的问题是当 SumOfLongRootToLeafPath() 函数没有返回任何内容时,SumOfLongRootToLeafPathUtil(root) 函数中 maxSum 的值如何变化 变量的原始值如何变化请帮助 ps:请参考链接中给出的python代码

【问题讨论】:

  • 你能把相关的代码贴在这里吗,那个链接可能会死,这样这个问题以后就没用了。
  • 值在一个可变的列表对象中改变。

标签: python data-structures binary-tree recursive-datastructures


【解决方案1】:

传递给SumOfLongRootToLeafPath 函数的maxSum 列表对象是可变的。因此,当它在该函数中发生更改时,SumOfLongRootToLeafPathUtil 函数将看到对它的更改。所以,不需要返回值。

例如显示列表的可变性质

def change_it(value):
    value[0] = 12 # modify the list without creating a new one

value = [4]
print(value) # this will show [4]
change_it(value)
print(value) # this will show [12] as change_it has altered the value in the list

如果 maxSum 使用的是元组而不是 List,则有必要从 SumOfLongRootToLeafPath 返回结果,因为元组是不可变的。

例如显示元组的不可变性质

def change_it(value):
    value = (12, ) # can't modify the tuple, so create a new one

value = (4, )
print(value) # this will show (4,)
change_it(value)
print(value) # this will still show (4,) as change_it cannot modify the tuple

【讨论】: