我尝试使用python实现二叉树,所以我构建了一个Node类和一个以节点为根并离开的Tree类。这是我遇到问题的部分:
def BFS(self):
s = " "
currentD = deque()
nextD = deque()
currentD.append(self.root)
while currentD:
while currentD:
r = currentD.popleft()
print type(r)
print isinstance(r, Node)
print isinstance(r, Tree)
if not r.isVisited():
r.visit()
s += " " + str(r.get_val())
if r.get_left():
nextD.append(r.get_left())
if r.get_right():
nextD.append(r.get_right())
#currentD should be empty now
s += "\n"
swap(currentD, nextD)
self.root.refresh()
return s
def __str__(self):
return self.BFS()
我现在遇到的问题是,当我尝试使用两个deques来执行BFS并打印树时,currentD获得的对象r(使用popleft())应该是树中的Node。但是,我收到错误消息" AttributeError:' Tree'对象没有属性' isVisited'"。如果我使用Tree的属性,它会给我另一个" AttributeError"那个' Node'对象没有属性....所以我试着检查这个r的类型,它似乎属于这两个类。这是消息:
<class '__main__.Node'>
True
False
<class '__main__.Tree'>
False
True
如果这不是其他bug造成的问题,有人可以向我解释一下这个python功能吗?在这种情况下,我怎么能告诉&#34;程序,这是一个节点而不是树? 为了以防万一,我将把Node和Tree的类放在这里。非常感谢你!
class Node(object):
def __init__(self,val = None, left = None, right = None, visited = False):
self.val = val
self.left = left
self.right = right
self.visited = visited
def get_val(self):
return self.val
def get_left(self):
return self.left
def get_right(self):
return self.right
def set_left(self, lItem):
self.left = lItem
def set_right(self, rItem):
self.right = rItem
def isVisited(self):
return self.visited
def visit(self):
self.visited = True
def refresh(self):
self.visited = False
def add_BST(self, item):
node = Node(item)
if not self.val:
self.val = item
elif self.val < item:
if not self.right:
self.right = node
else:
self.right.add_BST(item)
else:
if not self.left:
self.left = node
else:
self.left.add_BST(item)
class Tree(object):
def __init__(self, root = None):
self.root = root
def get_root(self):
return self.root
def add(self, item):
self.root.add_BST(item)
def BFS(self):
s = " "
currentD = deque()
nextD = deque()
currentD.append(self.root)
while currentD:
while currentD:
r = currentD.popleft()
print type(r)
print isinstance(r, Node)
print isinstance(r, Tree)
if not r.isVisited():
r.visit()
s += " " + str(r.get_val())
if r.get_left():
nextD.append(r.get_left())
if r.get_right():
nextD.append(r.get_right())
#currentD should be empty now
s += "\n"
swap(currentD, nextD)
self.root.refresh()
return s
def __str__(self):
return self.BFS()