【发布时间】:2017-11-10 18:30:29
【问题描述】:
我创建了一棵二叉树,并试图找到我手动传递的任何节点的父节点。它在左子树上运行良好,但仅对右子树上的某些特定节点没有。
# To create a tree from scratch
class tree:
"""To create nodes each time an instance has been
created"""
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def parent_search(self, root, child_node):
if root :
if root.left.data== child_node:
return root.data
if root.right.data== child_node:
return root.data
elif root:
return self.parent_search(root.left, child_node)
return self.parent_search(root.right, child_node)
root = tree(10)
root.left = tree(20)
root.left.left = tree(90)
root.left.right = tree(100)
root.left.left.left = tree(80)
root.right = tree(30)
root.right.left = tree(40)
root.right.right = tree(50)
print(root.parent_search(root,80))
如果我给root.parent_search(root,80),我得到 90 作为 80 的父级。但是,如果我在右边搜索假设 40,它会给我NoneType 错误。
return self.parent_search(root.left, child_node)
File "/home/vaibhav/Desktop/Data_Structures/python_play_area.py", line 14, in parent_search
if root.right.data== child_node:
AttributeError: 'NoneType' object has no attribute 'data'
观察
我没有看到子树的右孩子有任何问题,因为我可以看到 root.left.right 在我们将其称为父母或孩子时成功传递。
【问题讨论】:
-
您的递归需要处理 root.left 或 root.right 为 None 的情况。此外,
elif root:之后的语句将不起作用,因为有两个返回。第二个 return 语句永远不会被执行。 -
我应该在哪里添加 root.left 或 root.right 是 None 以及为什么两个返回不起作用。请解释
-
一旦一个方法返回,它就不再执行,所以第二个return语句永远不会被执行。我发布了一个答案,因为 cmets 很难格式化。
标签: python data-structures binary-tree recursive-datastructures