递归的python理解列表

时间:2019-10-09 02:18:24

标签: python

我有一个遍历树并收集列表的递归函数。我不明白为什么我必须将“列表”转换为list。我在代码中添加了注释。删除list()将导致列表为空。

class TreeNode:
  def __init__(self, val, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right

def find_paths(r, sum):

  def helper(root, summ, path, paths):
    if not root:
      return

    path.append(root.val)

    if not root.left and not root.right and summ == root.val:
      """
      if I print path

      [12, 7, 4]
      [12, 1, 10]
      """
      # why is list() necessary here
      paths.append(list(path))

    else:
      helper(root.left, summ - root.val, path, paths)  
      helper(root.right, summ - root.val, path, paths)

    del path[-1]

  paths = []
  helper(r, sum, [], paths)
  return paths

def main():

  root = TreeNode(12)
  root.left = TreeNode(7)
  root.right = TreeNode(1)
  root.left.left = TreeNode(4)
  root.right.left = TreeNode(10)
  root.right.right = TreeNode(5)
  sum = 23
  print("Tree paths with sum " + str(sum) +
        ": " + str(find_paths(root, sum)))


main()

以这种方式paths.append(path)执行此操作将导致 Tree paths with sum 23: [[], []]

1 个答案:

答案 0 :(得分:1)

当您执行以下操作时,方法list(path)将创建列表的副本:

paths.append(list(path))

执行此操作时,实际上是在添加列表的副本:

paths.append(path)

您要将引用添加到列表,以便在修改时像在以下内容中一样:

del path[-1]

它会影响添加到paths的引用。