我正在尝试对一棵二叉树进行深度优先搜索。该树是有效的。当yield不是一个生成器时,函数本身可以正常工作。
class BinaryTree(object):
def __init__(self, root):
self.root = root
def dfs(self):
print "Depth First"
return self.depth(self.root)
def depth(self, Node):
print "Starts"
yield Node
if Node.left != None:
print "keep it up left"
self.depth(Node.left)
if Node.right != None:
print "keep it up right"
self.depth(Node.right)
print "oh no"
编辑:以下是主要内容的摘录:
tree = BinaryTree(15) #adds the key 15 as the root
tree.addKey(10) #adds additional entries
...
tree.addKey(5)
depthFirstSearch = tree.dfs()
for i in range(8):
print depthFirstSearch.next()
print "outside of fnc"
为了完整性,树的形状如下:
{15: {10: {3: {2: , }, {5: , }}, }, {17: , {60: {23: , }, }}}
输出结果如下:
Depth First
Starts
15
outside of fnc
keep it up left
keep it up right
oh no
很明显由于"keep it up"的调试行,结点是存在的。但似乎跳过了递归步骤,否则将会打印"Start again"。我尝试替换为在self.depth(Node.right)语句中添加一个yield,但这似乎没有帮助。在生成器内部不好使用return语句,这对我来说很合理。谢谢!
depthFirstSearch
吗? - Tyler Crompton