6

So given the following:

def inorder(t):
    if t:
        inorder(t.left)
        yield t.key
        inorder(t.right)

x = [ n for n in inorder(r) ]

x only contains the root node, why?

Here's the full code; note that the BST implementation is correct, it's the inorder() implementation with generators that is somehow wrong.

class STree(object):
    def __init__(self, value):
        self.key = value
        self.left = None
        self.right = None

def insert(r, node):
    if node.key < r.key:
        if r.left is None:
            r.left = node
        else:
            insert(r.left, node)
    else:
        if r.right is None:
            r.right = node
        else:
            insert(r.right, node)

def inorder(t):
    if t:
        inorder(t.left)
        yield t.key
        inorder(t.right)


r = STree(10)
insert(r, STree(12))
insert(r, STree(5))
insert(r, STree(99))
insert(r, STree(1))

tree = [ n for n in inorder(r) ]
print tree
tzaman
  • 46,925
  • 11
  • 90
  • 115
laurids
  • 931
  • 9
  • 24
  • Are you using python 2 or 3? – tzaman Apr 22 '15 at 13:59
  • See the 3rd answer [here](http://stackoverflow.com/questions/21175923/inorder-traversal-in-python). You are only actually yielding one value. If you are using python 3.3 onwards you can use `yield from`. – Paul Rooney Apr 22 '15 at 14:01

1 Answers1

17

inorder(t.left) only creates the generator object, it doesn't actually run it. You need to actually yield all the values produced by each of the sub-generators, like so:

def inorder(t):
    if t:
        yield from inorder(t.left)
        yield t.key
        yield from inorder(t.right)

Note that the yield from convenience syntax was only introduced in Python 3.3 so if you're using an older version you'll have to iterate over the sub-generators explicitly:

# Python 2
def inorder(t):
    if t:
        for key in inorder(t.left):
            yield key
        yield t.key
        for key in inorder(t.right):
            yield key
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • I fixed a mistake on the py2 example; anyway thanks for the explanation, it makes much more sense now. – laurids Apr 22 '15 at 14:24
  • @laurids saw that, nice catch! and yw! – tzaman Apr 22 '15 at 14:26
  • @Prerit both python2 and 3 versions work fine for me, your error must be somewhere else. – tzaman Feb 20 '17 at 09:57
  • @tzaman It was python version. Leetcode has python version < 3.3 . – Slayer Feb 20 '17 at 11:48
  • 1
    Careful about complexity here. Both the explicit loop and `yield from` lead to a quadratic-time algorithm here. https://www.python.org/dev/peps/pep-0380/#optimisations discusses the tree example specifically. – user7610 Oct 27 '20 at 10:17