xan*_*der 6 python binary-tree list generator
我试图用生成器返回二叉树中所有叶子的值,并将生成的值放入列表中。这是我使用yield语句的递归代码,但我不知道如何使用生成器返回最终值。标题为“上一个代码”的第二段代码显示了带有 print 语句的相同代码,该代码输出正确的值,因此唯一的问题是生成器。请注意,此代码使用从二叉树类导入的 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)
Run Code Online (Sandbox Code Playgroud)
以前的代码
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)
Run Code Online (Sandbox Code Playgroud)
这是我的测试代码,应该返回列表[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())
Run Code Online (Sandbox Code Playgroud)
Nir*_* H. -1
# my attempt
a = find(self.root)
lst = []
for i in a:
lst.append(i)
return lst
Run Code Online (Sandbox Code Playgroud)
更短的替代方案:
# my attempt
return list(find(self.root))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |