【问题标题】:Passing variable by reference in python在python中通过引用传递变量
【发布时间】:2017-05-10 20:25:21
【问题描述】:

我正在练习一个 leetcode 问题,但我无法更新我的变量。我认为我没有正确传递我的参考。我期待答案是 3,但我得到 1。我运行了代码并且得到了答案 3,但是当我跳出递归时,我得到 1。

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

例如:

1
 \
  3
 / \
2   4
     \
      5

答案是 3 --> 3,4,5

下面是可运行代码:

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

class Solution(object):
    def DFS(self, root):
        count = 0
        if root:
            count += 1
            q = [root]
            while q:
                n = q.pop()
                T = 0
                if n.left:
                    if n.left.val == n.val + 1:
                        q.append(n.left)
                        T = 1
                if n.right:
                    if n.right.val == n.val + 1:
                        q.append(n.right)
                        T = 1
                if T:
                    count += 1
        return count

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

a = Node(1)
b = Node(3)
c = Node(2)
d = Node(4)
e = Node(5)

a.right = b
b.left = c; b.right = d
d.right = e

poop = Solution()
print(poop.longestConsecutive(a))

【问题讨论】:

  • 如果您生成一个问题的最小示例,而没有围绕它的所有不相关的逻辑,您将获得更好更快的答案。如果您不确定自己的 DFS 实施,请将其作为单独的问题发布
  • 不能在 Python 中通过引用传递变量。事实上,你根本不会传递变量。你只能传递对象。
  • 从技术上讲,Python 不支持传递引用语义。
  • 您正在使用 T,一个 int 变量,作为布尔标志。只需使用TrueFalse
  • @user2357112 您将对象分配给名称

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


【解决方案1】:

您从longestConsecutive 方法返回count,但没有将其分配给任何东西。试试这个:

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-06
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      相关资源
      最近更新 更多