# recursion使用yield

` `def infinity(start): yield start # recursion here ... >>> it = infinity(1) >>> next(it) 1 >>> next(it) 2` `

` `def infinity(start): yield start infinity(start + 1)` `

` `def infinity(start): yield start yield infinity(start + 1)` `

` `def infinity(start): while True: yield start start += 1` `

### 3 Solutions collect form web for “recursion使用yield”

` `def infinity(start): yield start for x in infinity(start + 1): yield x` `

` `def infinity(start): yield start yield from infinity(start + 1)` `

` `def traverse_tree(callback): # Get the root node from somewhere. root = get_root_node() def recurse(node): callback(node) for child in node.get('children', []): recurse(child) recurse(root)` `

` `def callback(node): print(node['id']) traverse_tree(callback)` `

` `# A stack-based alternative to the traverse_tree method above. def iternodes(): stack = [get_root_node()] while stack: node = stack.pop() yield node for child in node.get('children', []): stack.append(child)` `

` `for node in iternodes(): print(node['id'])` `