微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么在递归 python 函数中没有更新函数参数?

如何解决为什么在递归 python 函数中没有更新函数参数?

我试图在二叉搜索树中找到节点的中序后继。我的代码基本上是通过使用计数器变量进行中序遍历并跟踪下一个节点:

class Solution:
    # returns the inorder successor of the Node x in BST (rooted at 'root')
    ans = None 
    def inorderSuccessor(self,root,x):
        counter = 0
        answer = self.findNode(root,x,counter)
        return self.ans
     
    def findNode(self,counter):
        if root == None:
            return None
        self.findNode(root.left,counter)
        if counter == 1:
            counter += 1
            self.ans = root
            return root
        if root.data == x.data:
            ###counter becomes 1 here,when it finds the x node.
            counter += 1
        ###but it is not updated in the params.    
        self.findNode(root.right,counter)

这不起作用,因为计数器变量永远不会被递归调用更新。

但是如果我让 counter 成为一个全局变量,它会起作用:

class Solution:
    # returns the inorder successor of the Node x in BST (rooted at 'root')
    ans = None 
    counter = 0
    def inorderSuccessor(self,x):
        # Code here
        answer = self.findNode(root,x)
        return self.ans
     
    def findNode(self,x):
        if root == None:
            return None
        self.findNode(root.left,x)
        if self.counter == 1:
            self.counter += 1
            self.ans = root
            return root
        if root.data == x.data:
            self.counter += 1
        self.findNode(root.right,x)

谁能解释一下 Python 的这个属性?为什么在进行递归调用时不更新函数参数?

解决方法

当你调用 findNode(root,x,counter) 时,如果 findNode assigns 一个新值给 counter,这是对 {{ 局部变量的赋值1}} -- 参数变量。此类赋值不适用于在函数调用中命名的 findNode 变量。

更多的算法:没有必要有这样一个 counter 变量。您可以改用以下算法:

按照 BST 逻辑走下树。当 counter 小于当前节点的数据时,向左走,否则向右走。每次向左走时,请记住您来自哪里,因为它可能会成为我们正在寻找的继任者。

一旦您到达树中这条向下路径的末端,请回想哪个节点是最后一个决定向左移动的节点。那是继任者。

代码:

x.data

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。