Created
December 7, 2016 01:25
-
-
Save dawranliou/0bd6150600cfd42ecc55bfecc8ee6078 to your computer and use it in GitHub Desktop.
Practice Python's yield from expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, v): | |
self.v = v | |
self.l = None | |
self.r = None | |
def __repr__(self): | |
return '<Node %d>' % self.v | |
def children(node): | |
if node.l: | |
yield node.l | |
if node.r: | |
yield node.r | |
def traverse(root): | |
def _traverse(node, path): | |
if node.l is None and node.r is None: | |
yield path + [node.v] | |
for child in children(node): | |
yield from _traverse(child, path + [node.v]) | |
yield from _traverse(root, []) | |
tree = Node(1) | |
tree.l = Node(2) | |
tree.r = Node(3) | |
tree.l.l = Node(4) | |
tree.l.r = Node(5) | |
ans = traverse(tree) | |
print(list(ans)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment