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結(jié)合生成器來(lái)實(shí)現(xiàn)
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)