这两个关于在Python中递归传递变量的语句有什么区别

2024-04-20 05:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的python学习者。还有一个问题让我很困惑,因为这真的浪费了很多时间去思考。你知道吗

有一个关于二叉树的算法难题,和一个和,你应该找到所有根到叶的路径,其中每个路径的和等于给定的和。你知道吗

例如: 给定下面的二叉树和sum=22

An example picture here

我已经编写了一个类似blow的python递归方法,它可以在在线判断上正确运行。你知道吗

#definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val=x
        self.left=None
        self.right=None
class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        res=[]
        if not root:
            return res
        temp=[root.val]
        self.helper(root,sum,res,temp)
        return res
    def helper(self, root, sum, res, temp):
        if not root:
            return 0
        if root.left==None and root.right==None and sum==root.val:
            res.append(temp)
        if root.left!=None:
            self.helper(root.left,sum-root.val,res,temp+[root.left.val])
        if root.right!=None:
            self.helper(root.right,sum-root.val,res,temp+[root.right.val])

在最后四行中,我递归调用helper函数,通过pass root left child和root right child查找路径和。你知道吗

但是,如果我像下面这样重写代码,我的意思是只有最后四行

if root.left!=None:
    temp+=[root.left.val]
    self.helper(root.left,sum-root.val,res,temp)
if root.right!=None:
    temp+=[root.right.val]
    self.helper(root.right,sum-root.val,res,temp)

它给了我错误的答案,不能通过网上的判断。你知道吗

有人知道在python中将参数传递给函数时这两种方法有什么区别吗。或者是我代码中的任何声明和传递问题。你知道吗

在我看来,我看不出有什么不同。谢谢所有人。救命我!你知道吗


Tags: self路径righthelpernonereturnifdef
3条回答

当你说temp += ...时,你正在修改temp。但你在左右两种情况下都用它。你知道吗

所以你有:

temp = [0]
if root.left is not None:
    temp += [1]               # Now temp is [0, 1], probably okay
    ...
if root.right is not None:
    temp += [2]               # Now temp is [0, 1, 2], not [0, 2]!

第二个版本不正确,因为您将在左叶检查和右叶检查之间更新temp变量

if root.left!=None:
    temp+=[root.left.val] # temp updated here
    self.helper(root.left,sum-root.val,res,temp)
if root.right!=None:
    temp+=[root.right.val] # the updated value could be used here, which is wrong 
    self.helper(root.right,sum-root.val,res,temp)

+=就地更改列表:

>>> def inplace(l):
...     l += ['spam']
...
>>> def new_list(l):
...     l = l + ['spam']
...
>>> a = ['foo']
>>> inplace(a)
>>> a
['foo', 'spam']
>>> a = ['foo']
>>> new_list(a)
>>> a
['foo']

每次执行以下操作时,原始代码都会传入一个新列表

self.helper(root.left,sum-root.val,res,temp+[root.left.val])

但是您修改的代码在所有递归调用中共享temp,并且每次都扩展它。这很重要,因为通过创建一个新的列表,您为左分支的递归调用提供了一个新的、独立于右分支的列表。通过使用+=扩展列表,您现在可以在处理左分支之后为右分支提供一个更大的列表。你知道吗

相关问题 更多 >