深度优先算法
定义生成器函数响应迭代操作,主要包含三个工作:
数据准备
迭代路由:__iter__(),内部使用iter()
迭代协议:负责数据输出的生成器函数
class Node:
def __init__(self, value):
# 核心数据与物理容器
self._value = value
self._children = [] # 存放子节点物理指针的单层列表
def __repr__(self):
# 物理审查拦截:强制保留数据类型的边界
return 'Node({!r})'.format(self._value)
def add_child(self, node):
# 指针组装:将新的节点地址挂载到当前节点的网线上
self._children.append(node)
def __iter__(self):
# 透明路由代理:拦截外部的 for 循环请求,暗中转发给内部的 _children 列表
return iter(self._children)
def depth_first(self):
# 算法引擎与生成器工厂:前序遍历的物理挂起
yield self
# 隐式触发当前节点的 __iter__
for c in self:
# 建立到底层子生成器的透明物理管道
yield from c.depth_first()
# ==========================================
# 物理实例测试与验证
# ==========================================
if __name__ == '__main__':
# 1. 在内存荒野中浇筑 6 个孤立的地基(独立的内存块)
root = Node(0)
child1 = Node(1)
child2 = Node(2)
# 2. 建立指针连线,打破孤岛,升维成树状结构
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
# 3. 启动最外层的迭代监工,开始榨取生成器管道
print("深度优先遍历结果:")
for ch in root.depth_first():
print(ch)
# Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)