助手功能中的列表未更新

时间:2019-03-16 22:23:27

标签: python

我写了下面的代码来查找二叉树的根到叶路径。但是此代码不会更新op列表变量。当我使用op.extend(value)时  在辅助函数内部,它扩展了列表,但不确定为什么不附加列表?我期望op为路径列表,而path本身就是一个列表。例如:

[[1,2,5],[1,3]]

python 2.7代码:

def treepaths(root):
  op=[]
  currPath=[]

  def _path(root):
    if not root:
      return

    currPath.append(root.val)
    _path(root.left)

    if not root.left and not root.right:
      op.append(currPath)
    _path(root.right)
    currPath.pop()

  _path(root)
  return op

1 个答案:

答案 0 :(得分:1)

我明白你的问题了。 @ J.K。在某事上。问题在于,每当您到达一片叶子时,您就将 currPath 的引用放入 op 中。由于这是一个引用,因此以后您进一步操作 currPath 时,这也会更改您已推送到 op 的所有引用对象(同一对象)。而且由于遍历树的最后, currPath 最终为空,因此 op 中的所有引用对象也是如此。解决此问题所需要做的就是每次将列表复制到“ op”中。所以:

op.append(currPath)

应为:

op.append(list(currPath))

我想您会得到预期的结果。

这是我整理的完整示例。将来,这是我们希望看到的问题:

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

root = Node("A",
    Node("B",
        Node("C",
             Node("D"))),
    Node("F",
         Node("G",
              Node("H")),
         Node("I",
              None,
              Node("J")))
    )


def treepaths(root):
    op = []
    currPath = []

    def _path(root):
        if not root:
            return

        currPath.append(root.val)
        _path(root.left)

        if not root.left and not root.right:
            op.append(list(currPath))
        _path(root.right)
        currPath.pop()

    _path(root)
    return op

print(treepaths(root))

这将导致:

[['A', 'B', 'C', 'D'], ['A', 'F', 'G', 'H'], ['A', 'F', 'I', 'J']]

没有修复程序,您将得到:

[[], [], []]
相关问题