向递归函数传递字符串参数与数组参数之间的区别

问题描述 投票:0回答:1

这可能是一个愚蠢的问题,所以我很抱歉,但是有一个 Leetcode 问题,您必须在用“->”连接的字符串数组中返回从根节点到叶节点的所有路径(示例答案:[ “1->2->5”,“1->3”])。下面代码块中的两个解决方案都有效。我主要好奇为什么对于字符串解决方案,我可以在附加路径后返回,然后下一个递归调用不受影响,但对于数组解决方案,我无法返回,因为我必须弹出当前元素,否则会影响下一个递归调用。

这是因为数组是可变的,所以数组本身会改变,而字符串则不会,它会创建一个副本来传入?

这是创建字符串的解决方案。

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []

        def dfs(node, currPath):
            if not node:
                return
            
            currPath += str(node.val)
            if not node.right and not node.left:
                res.append(currPath)
                return
            
            dfs(node.left, currPath + "->")
            dfs(node.right, currPath + "->")
        
        dfs(root, "")
        return res

这是创建一个数组,然后将其连接起来以形成字符串的解决方案。

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []

        def dfs(node, currPath):
            if not node:
                return
            
            currPath.append(str(node.val))
            if not node.right and not node.left:
                res.append("->".join(currPath))
            
            dfs(node.left, currPath)
            dfs(node.right, currPath)
            currPath.pop()
        
        dfs(root, [])
        return res
python arrays string binary-tree depth-first-search
1个回答
0
投票

这种行为差异是由于可变对象与不可变对象的本质造成的:

  • 不可变对象(如字符串)在修改时会创建新对象。
  • 可变对象(如列表)被就地修改。

但是,如果您坚持将数组传递给函数,并且不想影响原始数组,则可以传递列表/数组的副本:

foo(list.copy())
© www.soinside.com 2019 - 2024. All rights reserved.