英文:
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.left 或 self.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论