# yield大法好

``````class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right

def visit_post(node):
if node.left:
yield from visit_post(node.left)
if node.right:
yield from visit_post(node.right)
yield node.val

if __name__ == '__main__':
node = Node(-1, None, None)
for val in range(100):
node = Node(val, None, node)
print(list(visit_post(node)))
``````

``````def visit_post(node):
if node.left:
yield node.left
if node.right:
yield node.right
yield node.val

def visit(node, visit_method):
stack = [visit_method(node)]
while stack:
last = stack[-1]
try:
yielded = next(last)
except StopIteration:
stack.pop()
else:
if isinstance(yielded, Node):
stack.append(visit_method(yielded))
elif isinstance(yielded, int):
yield yielded

if __name__ == '__main__':
node = Node(-1, None, None)
for val in range(100):
node = Node(val, None, node)
visit_generator = visit(node, visit_method=visit_post)
print(list(visit_generator))
``````

excellent！关键是很好理解对不对，我以前一直认为我不把LeetCode刷7遍是不可能完成递归转非递归的白板编程的，现在根本不是问题嘛。

``````def visit_maxvalue(node):
if node.left and node.right:
return max(node.val, visit_maxvalue(node.left), visit_maxvalue(node.right))
elif node.left:
return max(node.val, visit_maxvalue(node.left))
elif node.right:
return max(node.val, visit_maxvalue(node.right))
else:
return node.val
``````

``````def visit_max_maxvalue(node):
if node.left and node.right:
yield max(node.val, (yield node.left), (yield node.right))
elif node.left:
yield max(node.val, (yield node.left))
elif node.right:
yield max(node.val, (yield node.right))
else:
yield node.val

def visit(node, visit_method):
stack = [visit_method(node)]
current = None
while stack:
last = stack[-1]
try:
yielded = last.send(current)
except StopIteration:
stack.pop()
else:
if isinstance(yielded, Node):
stack.append(visit_method(yielded))
current = None
elif isinstance(yielded, int):
current = yielded
return current
``````

BTW，著名的Tornado就是用`yield`协程来实现异步，大爱！