我有以下遍历树对象的代码,但是找不到密钥时我无法返回节点对象。它给了我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
答案 0 :(得分:0)
您永远不会在main函数或任何递归步骤中返回值。两次拨打DFS
时都需要执行return DFS(..., ...)
。
答案 1 :(得分:0)
您好我认为当您进入必须做的正确递归的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