0

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
1
  • Could you add your TreeNode code? Commented Nov 6, 2018 at 16:23

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I can't touch TreeNode, which is why I didn't want to include it to begin with :\
yield from is what did it for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.