在python中通过引用传递变量

时间:2017-05-10 20:25:22

标签: python binary-tree pass-by-reference

我正在练习一个leetcode问题,我无法更新我的变量。我想我没有正确地传递我的参考资料。我期待答案是3但我得到1.我完成了代码并且答案3已经实现但是当我从我的递归中跳回来时我得到了1.

目标是在二叉树中找到最长的连续节点链。

例如:

<p>some text</p>

<!-- multiline "comment" below using textarea style="display:none;" -->
<textarea style="display:none;">

  <script>  

    alert("which won't show up..");  

  </script>

  <p>commented out html</p>

  <!-- comment 2

      // are nested html comment allowed?

    end of comment 2 -->

  <p>more commented out html</p>

</textarea>

<p>some more text</p>

答案是3 - &gt; 3,4,5-

以下是可运行的代码:

1
 \
  3
 / \
2   4
     \
      5

2 个答案:

答案 0 :(得分:3)

您从count方法返回longestConsecutive但未将其分配给任何内容。试试这个:

def longestConsecutive(self, root, count=0):
    """
    :type root: TreeNode
    :rtype: int
    """
    c = count
    if root:
        c = max(c, self.DFS(root))
        c = self.longestConsecutive(root.left, c)
        c = self.longestConsecutive(root.right, c)
    return c

答案 1 :(得分:2)

您的问题是未保存c的值。在递归调用内部,c的值已正确设置为3。但是当控制流开始向上移回递归堆栈时,c的值将丢失。要解决此问题,您可以将c设为Solutions的属性。这样,c的值可以通过递归调用保存。

def longestConsecutive(self, root, count=0):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.c = count # make c an attribute of Solution.
        if root:
            self.c = max(self.c, self.DFS(root))
            self.longestConsecutive(root.left, self.c)
            self.longestConsecutive(root.right, self.c)
        return self.c

哪个有输出:

3