Skip to main content
 首页 » 编程设计

python之使用 __iter__ 读取二叉树

2025年05月04日12Terrylee

我有一个标准的二叉树,如下所示
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__() 

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

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

它仅以正确的高度打印我尝试中的第一个节点。

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

请您参考如下方法:

在 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 

编辑:确认支持 Python 3.3。