我在python中实现了一个简单的二进制排序树;下面的代码是一个片段。
我已经在某处了解了TreeNode的__iter__
实现,并尝试了解它是如何工作的。代码工作正常,但我想知道一件事:
yield 语句如何在这里实际运作?它似乎从根开始,首先遍历左侧树,打印每个元素,但每次仍然从根开始。
class BinaryST(object):
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def __iter__(self):
class EmptyIter():
def next(self):
raise StopIteration
if self.root:
return self.root.__iter__()
return EmptyIter()
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __iter__(self):
# visit the left tree
if self.has_left_child():
for child in self.left:
print 'yielding left child'
yield child
# back to current element; root
print 'yielding root ele'
yield self.val
if self.has_right_child():
for child in self.right:
print 'yield right child'
yield child
输出:
bt = bst.BST()
bt.insert(5)
bt.insert(7)
bt.insert(3)
bt.insert(1)
for i in bt:
print i
yielding root ele
yielding left child
yielding left child
1
yielding root ele
yielding left child
3
yielding root ele
5
yielding root ele
yield right child
7
我试图理解这里的代码流程。堆栈怎么样?任何帮助将不胜感激。