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

为什么在递归python函数中没有更新函数参数?,python,algorithm,depth-first-search,Python,Algorithm,Depth First Search,我试图在二元搜索树中找到节点的顺序继承者。我的代码基本上是按顺序遍历,并通过使用计数器变量跟踪下一个节点: 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.findN

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

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, root, x, counter):
        if root == None:
            return None
        self.findNode(root.left, x, 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, x, counter)
这不起作用,因为递归调用从不更新计数器变量

但如果我将
计数器
设为全局变量,则它可以工作:

class Solution:
    # returns the inorder successor of the Node x in BST (rooted at 'root')
    ans = None 
    counter = 0
    def inorderSuccessor(self, root, x):
        # Code here
        answer = self.findNode(root, x)
        return self.ans
     
    def findNode(self, root, 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
counter
分配一个新值,则这是对
findNode
参数变量本地变量的分配。此类赋值不属于函数调用中命名的
计数器
变量

关于算法的更多信息:不需要有这样的
计数器
变量。您可以改为使用以下算法:

按照BST逻辑走下树。当
x.data
小于当前节点的数据时,向左,否则向右。每次你离开,都要记录下你来自哪里,因为它可能是我们正在寻找的继任者

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

代码:

def inorderSuccessor(self、root、x):
候选人=无
而root:
如果x.data
请务必说明,如果问题中需要任何澄清?您的代码的编写方式,如果
root.data
x.data
相等,则
计数器将在以后的递归调用中递增。你确定这个条件是真的吗?考虑调试您的代码,并查看条件TrpRes是否发生,因为函数的参数是通过值传递的,而不是按名称传递。
计数器当前具有的值被复制到函数的本地变量中。如果函数更改该局部变量的值,则该值与作为参数传递其值的变量无关。是的,只要根指针遇到x节点,此条件为真,在这种情况下计数器为1@SilvioMayolo@trincot这很有意思,你知道有没有其他方法可以绕过这个,不使用全局变量
    def inorderSuccessor(self, root, x):
        candidate = None
        while root:
            if x.data < root.data:
                candidate = root
                root = root.left
            else:
                root = root.right
        return candidate