迭代协议本身不控制递归深度,但可用显式栈模拟递归并自主维护深度;如tree_depth_iterator用(stack, depth)元组避免调用栈,yield实现迭代,天然防RecursionError。

直接用迭代协议实现“递归深度控制”其实是个概念错位——迭代协议本身不处理调用栈或深度限制,它只定义对象如何被 for 循环或 next() 逐个访问。但你可以借助迭代器+显式状态管理,**绕过函数调用栈**,从而天然规避 RecursionError。这本质上是用迭代替代递归,并在过程中自主跟踪“当前深度”。
用迭代器模拟递归过程并记录深度
比如遍历一棵树时,你想在每层打印当前深度,同时防止爆栈。不靠递归函数调用,而是用一个栈(list 或 deque)存节点及其对应深度:
def tree_depth_iterator(root):
if not root:
return
stack = [(root, 0)] # (节点, 当前深度)
while stack:
node, depth = stack.pop()
yield node, depth
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
使用方式:
for node, d in tree_depth_iterator(root):
print(f"值: {node.val}, 深度: {d}")
关键点:
• 每个元素是 (node, depth),深度由你显式维护,不依赖调用栈
• yield 让它成为生成器,符合迭代协议,可被 for 遍历或 next() 逐步取值
• 不会触发 RecursionError,哪怕树深 10 万层
用自定义迭代器类封装深度逻辑
如果你需要更精细的状态控制(比如跳过某深度、限制最大遍历深度),可以写一个带参数的迭代器类:
class BoundedDepthIterator:
def __init__(self, root, max_depth=100):
self.root = root
self.max_depth = max_depth
self.stack = [(root, 0)] if root else []
self._exhausted = False
def __iter__(self):
return self
def __next__(self):
if not self.stack or self._exhausted:
raise StopIteration
node, depth = self.stack.pop()
if depth > self.max_depth:
return self.__next__() # 跳过超深节点
if node.right and depth + 1 self.stack.append((node.right, depth + 1))
if node.left and depth + 1 self.stack.append((node.left, depth + 1))
return node, depth
这样就实现了:主动限深、跳过无效分支、全程无函数递归调用。
为什么不用 setrecursionlimit?
sys.setrecursionlimit() 只是放宽 Python 的硬性拦截,但底层 C 栈空间仍有限。一旦真把深度设到几万,容易引发段错误或程序崩溃,尤其在嵌入式或容器环境中。
而基于迭代协议的方式:
• 所有状态存在 Python 对象(list/tuple)里,内存由垃圾回收管理
• 深度变量只是整数,不增加栈帧
• 可随时中断、暂停、检查、修改深度逻辑
• 天然支持协程、异步迭代等扩展场景
配合 itertools 做流式截断
若你已有生成器,还想按深度做分批处理,可用 itertools.islice 或 takewhile:
from itertools import takewhile
# 只取深度 ≤ 5 的所有节点
shallow_nodes = takewhile(lambda x: x[1] for node, d in shallow_nodes:
process(node)
或者用 islice 控制最多取前 N 层的结果,避免一次性加载全量。

















