【问题标题】:Depth first search not returning correct object type深度优先搜索未返回正确的对象类型
【发布时间】:2014-06-13 16:26:41
【问题描述】:

我有以下代码遍历树对象,但是当找到键时,我无法让它返回节点对象。它给了我 NoneType 。对象很简单,包括在下面。

class StructureTree:
    def __init__(self, issueID, depth):
        self.issueID = issueID
        self.depth = depth
        self.children = []
        self.worklog_data_rows = []
        self.structure_data_row = [] #contains issue data for any issue found in the global structure


    def addChild(self, elem):
        self.children += [elem]

    def __repr__(self):
        return "<%d : %d>" % (self.issueID, self.depth)


class StructureForest:
    def __init__(self):

        self.trees = []
        self.roots =[]

    def addRoot(self, root):
        self.roots += [root]

def DFS(node, key):
'''
Depth First Traversal (In-order).
@node -- int
@key -- int
'''
    if node.issueID == key:
        print "Found!"
        return node
    else:
        for child in node.children:
            print "here"
            return DFS(child, key)


def search_node(n_tree_forest, key):
'''
Traverses entire forest.
@key -- int
'''
    for root in n_tree_forest.roots:
       val = DFS(root, key)
       return val

【问题讨论】:

  • 请修正你的缩进。

标签: python algorithm search


【解决方案1】:

您永远不会在主函数或任何递归步骤中返回值。两次拨打DFS 都需要拨打return DFS(..., ...)

【讨论】:

  • 在问题中编辑了我的算法,但这仍然给了我相同的结果。
  • 嗯,另一个问题是你没有在再次返回之前检查你是否真的从递归调用中找到任何东西。
  • 是的,但是我传递了一个值,我知道在测试函数时应该返回一个节点
【解决方案2】:

您好,我认为当您进入 else 语句时,您似乎没有返回任何东西,您必须为正确递归执行该语句。修改你的 DFS 方法...

def DFS(node, key):

    if node.issueID == key:
        print "Found!"
        return node.issueID
    else:
        for child in node.children:
            print "here"
            val = DFS(child, key)
            if val: return val
         return False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多