2012-03-13 46 views
0

我需要编写一个函数,我需要返回树叶的列表。使用递归打印树叶的列表

因此,对于这个树:

 1 
    2  3 
4  5  6 

这应该打印[4,5,6]

下面是我想出这么远。我似乎无法找到如何回到功能。它只打印[4]

def fringe(root): 

    if root.left: 
     return fringe(root.left) 
    elif root.right: 
     return fringe(root.right) 
    else: 
     return [root.key] 

任何输入?

+0

需要更多的清除 – 2012-03-13 21:26:30

回答

4

使用yield创建一个发电机:

def fringe(root): 

    if root.left or root.right: 
     if root.left: 
      for key in fringe(root.left): 
       yield key 
     if root.right: 
      for key in fringe(root.right): 
       yield key 
    else: 
     yield root.key 

print list(fringe(mytree)) 

在Python中的新版本,而不是

for key in fringe(root.left): 
    yield key 

您可以使用:

yield from fringe(root.left) 
+1

这个想法是正确的,但这也行不通。这将会向左或向右移动,或者产生当前节点。 – 2012-03-13 21:29:56

+0

你死了,修好了。 (在修改代码之前没有检查他的逻辑) – bluepnume 2012-03-13 21:32:30

+0

请注意,“更新版本的Python”是指当前的开发中继。没有发布的版本支持''收益率'呢。 – 2012-03-13 22:08:06

1

这并不因为工作如果你已经离开了叶子,那么你根本看不到正确的叶子。尝试这一个

def fringe(root): 
    result = [] 
    if root.left: 
     result.extend(fringe(root.left)) 
    if root.right: 
     result.extend(fringe(root.right)) 
    if not result: 
     result = [root.key] 
    return result