我一直在研究一个问题,该问题计算二叉树上每个分支的总和并以数组形式返回它们。这几乎是一个DFS问题,您需要在其中将解决方案累积到一个阵列中。我只是在努力理解将return语句放置在代码中的位置。我知道正确的答案,只是不知道为什么下面的两个片段不相等:
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
答案 0 :(得分:0)
如果一棵树只有一个节点(根节点),则两种解决方案都可以使用。现在让我们讨论第一个解决方案:
仅当两个子项均为None时才返回soln数组。现在,如果节点有一个或多个子节点,则此条件将始终失败。因此,return语句将永远不会执行。这就是原因,第一个解决方案返回无。这是使用二进制搜索树的执行。
class Tree:
def __init__(self, val):
self.value = val
self.left = None
self.right = None
def add(self, val):
if val <= self.value:
if self.left is None:
self.left = Tree(val)
else:
self.left.add(val)
else:
if self.right is None:
self.right = Tree(val)
else:
self.right.add(val)
def t_print(self):
if self.left is not None:
self.left.t_print()
print self.value
if self.right is not None:
self.right.t_print()
def help(root, sums, soln):
if root.left is None and root.right is None:
soln.append(sums)
print 'Returning value for node ' + str(root.value)
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)
print 'Returning none for node ' + str(root.value)
return None # ----> This is what being executed after every recursive call finishes (for node with children)
def branchTot(root):
soln = []
fin = help(root, root.value, soln)
return fin
执行上述操作将得到以下输出:
In [28]: root = Tree(9)
In [29]: root.add(5)
In [30]: root.add(3)
In [31]: root.add(2)
In [32]: root.add(10)
In [33]: root.add(13)
In [34]: root.add(11)
In [26]: branchTot(root)
Returning value for node 2
Returning none for node 3 ----> node with children
Returning none for node 5
Returning value for node 11 ------> node without children
Returning none for node 13
Returning none for node 10
Returning none for node 9
In [27]:
但是,在第二种解决方案中,您将return语句置于if块之外,因此无论如何都将执行return语句。这将返回最终数组。
希望这会有所帮助。