【发布时间】:2022-01-07 17:28:12
【问题描述】:
我正在尝试使用生成器返回二叉树中所有叶子的值,并将产生的值放入列表中。这是我使用 yield 语句的递归代码,但我不知道如何使用生成器返回 final 值。标题为“Previous Code”的第二段代码显示了带有打印语句的相同代码,它输出正确的值,因此唯一的问题是生成器。请注意,此代码使用从二叉树类导入的 root.left 和 root.right,并且似乎工作正常。提前感谢您的任何帮助!
我的代码
def leaves_list(self):
def find(root):
if not root:
yield
if not root.left and not root.right:
yield root.data
if root.left:
find(root.left)
if root.right:
find(root.right)
# my attempt
a = find(self.root)
lst = []
for i in a:
lst.append(next(a))
return find(self.root)
以前的代码
def leaves_list(self):
def find(root):
if not root:
return
if not root.left and not root.right:
print(root.data, end = " ")
return
if root.left:
find(root.left)
if root.right:
find(root.right)
return find(self.root)
这是我的测试代码,应该返回列表[5, 1, 8, 4]。
测试人员代码
root = LinkedBinaryTree.Node(3)
T = LinkedBinaryTree(root)
a = LinkedBinaryTree.Node(2)
a.parent = root
root.left = a
b = LinkedBinaryTree.Node(7)
b.parent = root
root.right = b
c = LinkedBinaryTree.Node(9)
c.parent = a
a.left = c
d = LinkedBinaryTree.Node(5)
d.parent = c
c.left = d
e = LinkedBinaryTree.Node(1)
e.parent = c
c.right = e
f = LinkedBinaryTree.Node(8)
f.parent = b
b.left = f
g = LinkedBinaryTree.Node(4)
g.parent = b
b.right = g
print(T.leaves_list())
【问题讨论】:
-
如果没有树和节点类,这很难调试,但我观察到
lst.append(next(a))应该是lst.append(i)因为你正在跳过所有其他值。 -
您这样做是为了练习生成器,还是只是对获取列表感兴趣?因为直接的生成器版本效率低下。
标签: python list binary-tree generator