【问题标题】:Passing a binary tree by reference in python3 [duplicate]在python3中通过引用传递二叉树[重复]
【发布时间】:2021-02-10 05:01:00
【问题描述】:

我正在尝试理解 python 的行为。我有下面的一段代码: (TreeNode 是一个普通的二叉树类)

class Solution:

    def anotherfunction(self, root, key):
        print(root)
        if(root.val == key):
            root = None
        print(root)
    
    def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
        self.anotherfunction(root, key)
        print(root)

输出如下图:

TreeNode{val: 5, left: TreeNode{val: 2, left: None, right: None}, right: None}

None

TreeNode{val: 5, left: TreeNode{val: 2, left: None, right: None}, right: None}

我不知道为什么我的删除节点函数中的根没有被修改?如果我只是使用 *& 传递根目录,我是 Python3 和 C++ 的新手,它可以正常工作。我想知道什么是python相当于通过引用传递?

【问题讨论】:

  • 不能在 Python 中通过引用传递变量。如果要将变量设置为 None,则必须将该实际变量设置为 None。
  • Python 默认是按赋值的。您始终可以将变量定义为self.root,因此它基本上是同一个对象。
  • 无论如何我可以在另一个函数中将我的根设置为 None 并让它反映在 deleteNode 函数中吗?
  • 可以将root设置为函数的返回值,然后从中返回None。
  • 让你的两个函数返回root的值,让调用者把返回的值赋给它自己的root变量。

标签: python python-3.x binary-tree pass-by-reference


【解决方案1】:

在python中你不能真正删除对象,你所能做的就是通过从变量或容器中删除一个对象来减少引用计数。调用deleteNode 和anotherfunction 都增加了引用计数。所有anotherfunction 都可以减少引用计数,并且在函数返回时无论如何都会发生这种情况。

你可以

class Solution:

    def anotherfunction(self, root, key):
        if(root.val == key):
            return root
        return None
    
    def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
        root = self.anotherfunction(root, key)
        print(root)

这将您的局部变量 root 替换为相同的对象或 None。请注意,对象本身可能不会被删除,具体取决于调用此方法的方式。在函数调用期间将对象分配给root 时,该对象获得了引用计数。如果调用者有引用,则该对象仍然存在。

sol = Solution()
my_node = Node(key="foo")
sol.deleteNode(my_node, "foo")
# still lives until all refs removed
del my_node
# finally got rid of it

【讨论】:

    【解决方案2】:

    如果在函数中使用之前在上层作用域或内部作用域中的变量具有原始值,它使用它的副本并且不会在上层作用域中更改,但是如果在内部作用域变量中使用引用,并且在函数中更改变量和新变量也被引用使用,它在上限范围内发生了变化

    这是因为原始变量和非原始变量之间的调用和返回方式不同

    例如:

     def A(a):
        print(a)
        a = 4
        print(a)
    
    
    if __name__ == '__main__':
        a = {"a": "s"}
        A(a)
        print(a)
    

    这个结果是: {'作为'} 4 {'a': 's'}

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多