iter的yield语句如何在TreeNode对象(BST)中工作

2024-04-23 11:12:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python实现一个简单的二进制排序树;下面的代码是一个片段。你知道吗

我在某个地方读到了__iter__TreeNode的实现,我试图理解它是如何工作的。代码运行良好,但我想知道一件事:

产生的语句在这里实际是如何工作的?它似乎从根开始,首先遍历左树,打印每个元素,但每次都从根开始。你知道吗

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

我试着理解这里的代码流。堆栈看起来怎么样?任何帮助都将不胜感激。你知道吗


Tags: selfrightchilddefvalrootleftclass