使用__iter__读取二叉树

Qui*_*cks 1 python python-3.x

我有一个标准的二进制树,读取像
1
/\
2 3
/\/\
4 5 6 7

我需要通过导入我的树类来读取二叉树,创建这个树,然后使用for循环来读取它:[4,2,5,1,6,3,7]

我已经创建了树,我的程序将生成一个包含任意数量的树.我的问题在于方法.

def iter(self):

到目前为止,我有:

def __iter__(self):
    if self.left:
        self.left.__iter__()
    yield self
    if self.right:
        self.right.__iter__()
Run Code Online (Sandbox Code Playgroud)

但是当我在树对象上运行for循环时:

对于树中的项目:print("{}:{}").format(item.name,item.height())

它只打印我尝试中具有正确高度的第一个节点.

我的问题基本上是,如何使用递归打印这个二叉树?

Jas*_*ohi 8

在Python> = 3.3中,可以使用yield from x递归迭代器的语法:

def __iter__(self):
    if self.left:
        yield from self.left
    yield self
    if self.right:
        yield from self.right
Run Code Online (Sandbox Code Playgroud)

编辑:Python 3.3支持已确认.