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

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

Calling a recursive function inside a class

问题

  1. def apend(self, arr, target):
  2. """arr是从根节点到目标节点的路径列表,self是根节点"""
  3. if self is None:
  4. return False
  5. arr.append(self.data)
  6. if self.data == target:
  7. return True
  8. if self.left and self.left.apend(arr, target) or (self.right and self.right.apend(arr, target)):
  9. return True
  10. arr.pop()
  11. 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.

  1. def apend(self, arr, target):
  2. """ arr is the list which has the path from root to target node, self is the root """
  3. if self is None:
  4. return False
  5. arr.append(self.data)
  6. if self.data==target:
  7. return True
  8. if self.left.apend(arr, target) or self.right.apend(arr, target):
  9. return True
  10. arr.pop()
  11. 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.

  1. def apend(self, arr, target):
  2. """ arr is the list which has the path from root to target node, self is the root """
  3. arr.append(self.data)
  4. if self.data==target:
  5. return True
  6. if self.left is not None and self.left.apend(arr, target):
  7. return True
  8. if self.right is not None and self.right.apend(arr, target):
  9. return True
  10. arr.pop()
  11. 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:

确定