在《python cookbook》(简称python奇技淫巧书)中看到的,觉得太简洁了,遂记录下来:
class Node(object):
def __init__(self, value):
self._value = value
self._children = []
# 添加子元素
def add_children(self, value):
self._children.append(value)
def __iter__(self):
return iter(self._children)
def __repr__(self):
return 'Node:{}'.format(self._value)
# 深度优先遍历算法,用了生成器的原理
def deep_first(self):
yield self
for ch in self:
yield from ch.deep_first()
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_children(child1)
root.add_children(child2)
child1.add_children(Node(5))
child1.add_children(Node(6))
child2.add_children(Node(4))
for ch in root.deep_first():
print(ch)