我正在尝试在Binary Search树中返回父节点和self。我收到此错误“无法解压缩不可迭代的NoneType对象”。请帮忙。
class Node:
def __init__(self,data=None):
self.data=data
self.left=None
self.right=None
def insert(self,data):
if data<self.data:
if self.left==None:
self.left=Node(data)
else:
self.left.insert(data)
elif data>self.data:
if self.right==None:
self.right=Node(data)
else:
self.right.insert(data)
else:
return
def printtree(self):
if self.left:
self.left.printtree()
print(self.data)
if self.right:
self.right.printtree()
def findval(self,data,parent=None):
if self.data==data:
return self,parent
elif data<self.data:
if self.left==None:
return None,None
else:
parent=self
self=self.left
self.findval(data,parent)
elif data > self.data:
if self.right == None:
return None,None
else:
parent = self
self = self.right
self.findval(data,parent)
else:
print("data not found")
return None,None
def deletenode(self,data):
self,parent=self.findval(data)
#Error found here
print(self.data,parent.data)
#Code of deletion
root=Node(10)
root.insert(5)
root.insert(15)
root.insert(3)
root.insert(7)
root.insert(13)
root.insert(16)
root.deletenode(5)
尝试在findval函数中返回父节点和self 发现错误=“ TypeError:无法解压缩不可迭代的NoneType对象” 我们如何用Python返回对象?
答案 0 :(得分:0)
问题是您错过了递归findval
调用的返回,请将代码更改为:
def findval(self, data, parent=None):
if self.data == data:
return self, parent
elif data < self.data:
if self.left is None:
return None, None
else:
return self.left.findval(data, self)
elif data > self.data:
if self.right is None:
return None, None
else:
return self.right.findval(data, self)
else:
print("data not found")
return None, None