python - 使用 __iter__ 读取二叉树

标签 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__()

但是当我在树对象上运行 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。

关于python - 使用 __iter__ 读取二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33658756/

相关文章:

python - 正则表达式组恰好匹配 n 次

python - 随机采样一个元素而不使其成为 Python 中的列表

python - 基本词典脚本

python - 如何用beautifulsoup4提取html?

python - 使用tile从二维数组构造3维数组

python - 如果Python中没有数据或空行,如何删除带下划线的字符串/名称

python - 如何获取 groupby 总计,然后计算 Pandas DataFrame 列的百分比

c++ - 如何在 python3 中使用 ctypes 导入 o​​stringstream?

python-3.x - Cloud Natural Language API 返回 socket.gaierror : nodename nor servname provided after performing Sentiment Analysis every now and then

django - 删除字符串列表周围的双引号