我试图在插入的每一步之后打印二叉搜索树的每个阶段。但是,我的代码生成的输出似乎错过了初始根数据插入步骤,并且还重复了某些阶段。我需要一个干净简单的方法来做到这一点。有没有办法使用__dict__.values()
.
我的代码:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def addNode(self, data):
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.addNode(data) # recursively calling addNode method
else:
if self.right is None:
self.right = Node(data)
else:
self.right.addNode(data)
if not self.left is None and not self.right is None:
print self.left.data, self.data, self.right.data
elif self.left is None and not self.right is None:
print None, self.data, self.right.data
elif not self.left is None and self.right is None:
print self.left.data, self.data, None
if __name__ == '__main__':
n = Node(5)
#print n.__dict__.values()
n.addNode(3)
n.addNode(2)
n.addNode(8)
n.addNode(4)
生成的输出:
3 5 None
2 3 None
3 5 None
3 5 8
2 3 4
3 5 8
预期输出:
None 5 None
3 5 None
2 3 None
3 5 8
2 3 4