【发布时间】:2019-12-18 06:20:09
【问题描述】:
我一直在研究一个计算二叉树上每个分支的总和并将它们返回到数组中的问题。它几乎是一个 DFS 问题,您可以将解决方案累积到一个数组中。我只是在努力理解在我的代码中放置 return 语句的位置。我知道正确答案,只是不知道为什么下面这两个sn-ps不等价:
def branchTot(root):
soln = []
fin = help(root, root.value, soln)
return fin
def help(root, sums, soln):
if root.left is None and root.right is None:
soln.append(sums)
return soln
else:
if root.right is not None and root.left is not None :
help(root.left, sums + root.left.value, soln)
help(root.right, sums + root.right.value, soln)
elif root.right is not None:
help(root.right, sums + root.right.value, soln)
else:
help(root.left, sums + root.left.value, soln)
下面的第二个解决方案:
def branchTot(root):
soln = []
fin = help(root, root.value, soln)
return fin
def help(root, sums, soln):
if root.left is None and root.right is None:
soln.append(sums)
else:
if root.right is not None and root.left is not None :
help(root.left, sums + root.left.value, soln)
help(root.right, sums + root.right.value, soln)
elif root.right is not None:
help(root.right, sums + root.right.value, soln)
else:
help(root.left, sums + root.left.value, soln)
return soln
【问题讨论】:
-
提示:要么只使用累加器而不返回任何东西,要么只使用返回值而不使用累加器。将两者混合只会使事情变得混乱。
标签: python recursion return-value recursive-backtracking