在一个类内调用递归函数。

huangapple go评论58阅读模式
英文:

Calling a recursive function inside a class

问题

    def apend(self, arr, target):
        """arr是从根节点到目标节点的路径列表,self是根节点"""

        if self is None:
            return False
        arr.append(self.data)
        if self.data == target:
            return True
        if self.left and self.left.apend(arr, target) or (self.right and self.right.apend(arr, target)):
            return True
        arr.pop()
        return False
英文:

I am trying to call a recursive method in order to find path from root to node in a binary tree. There are few solns. for this problem on the internet, but I am trying to use slightly different approach by implementing a method inside a Node class.

Here is my logic for the soln.

    def apend(self, arr, target):
        """ arr is the list which has the path from root to target node, self is the root """
    
 
        if self is None:
            return False
        arr.append(self.data)
        if self.data==target:
            return True
        if self.left.apend(arr, target) or self.right.apend(arr, target):
            return True
        arr.pop()
        return False

I a perfectly okay with how this logic is working, means if the target is found in either right or left subtree return True.

My question is; what if self is a leaf node, i.e. self.left is None. same with self. right. In that case the recursive call is giving an error.
Can I get some help on how to rectify that situation? thanx

答案1

得分: 2

你需要检查 self 是否为 None,而应该在进行递归调用之前检查 self.leftself.right 是否为 None

英文:

Instead of checking if self is None you need to check if self.left or self.right is None before you make a recursive call.

def apend(self, arr, target):
    """ arr is the list which has the path from root to target node, self is the root """


    arr.append(self.data)
    if self.data==target:
        return True
    if self.left is not None and self.left.apend(arr, target):
        return True
    if self.right is not None and self.right.apend(arr, target):
        return True
    arr.pop()
    return False

huangapple
  • 本文由 发表于 2023年2月19日 16:44:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定