Visitor模式实现
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def accept(self, visitor):
if self.left is not None:
self.left.accept(visitor)
visitor.visit(self)
if self.right is not None:
self.right.accept(visitor)
class PrintVisitor:
def visit(self,node):
print(node.data)
root = TreeNode('1')
root.left = TreeNode('2')
root.right = TreeNode('3')
visitor = PrintVisitor()
root.accept(visitor) #输出2, 1, 3
iter结合生成器来实现
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __iter__(self):
return self.__generator()
def __generator(self):
if self.left is not None:
yield from iter(self.left)
yield from self.data
if self.right is not None:
yield from iter(self.right)
root = TreeNode('1')
root.left = TreeNode('2')
root.right = TreeNode('3')
for ele in root:
print(ele)