python - Using generators to perform an inorder tree traversal on a BST -


so given following:

def inorder(t):     if t:         inorder(t.left)         yield t.key         inorder(t.right)  x = [ n n in inorder(r) ] 

x contains root node, why?

here's full code; note bst implementation correct, it's inorder() implementation generators 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 none:             r.left = node         else:             insert(r.left, node)     else:         if r.right 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 n in inorder(r) ] print tree 

inorder(t.left) creates generator object, doesn't run it. need iterate , yield values produced each of subgenerators:

# python 2 def inorder(t):     if t:         key in inorder(t.left):             yield key         yield t.key         key in inorder(t.right):             yield key 

this becomes lot cleaner introduction of new syntax in python 3.3+:

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

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -