TheRealFakeNews
TheRealFakeNews

Reputation: 8143

How to make a recursive generator?

I'm trying to make preOrder recursive so that I can do something such as:

Given the array representation of a tree [2,1,3] (the program actually takes a TreeNode, specifically TreeNode(2)

x = preOrder(root)
print x.next() # 1
print x.next() # 2
print x.next() # 3

But given the following code, I'm only able to call x.next() once, then it nothing returns after the first iteration.

    def preOrder(root):
        if root is not None:
            preOrder(root.left)
            self.lChild = root.left
            self.rChild = root.right
            yield root.val
            preOrder(root.right)

How can I fix this?


# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

Upvotes: 0

Views: 59

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could fix it like this:

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def __repr__(self):
        return str(self.val)


three = TreeNode(3)
one = TreeNode(1)
two = TreeNode(2)
two.left = one
two.right = three


def pre_order(root):
    if root is not None:
        yield from pre_order(root.left)
        yield root.val
        yield from pre_order(root.right)


for e in pre_order(two):
    print(e)

Output

1
2
3

Basically you need to yield from the recursive calls also. Given that you are using Python 2.7 see:

  1. Converting "yield from" statement to Python 2.7 code

Upvotes: 1

Related Questions