我实际上正在学习如何应用递归来解决一些现实生活中的问题。比方说,我有一个存储家谱的字典,每个人的 child 都将存储在这个字典中,并且它在树中的级别也将存储在该字典中。我想找出一个家庭的子树并将其存储到一个单独的字典中,所以我必须不断检查这个人是否有 child 。但是,我不知道为什么我的递归函数的新字典只能存储那些没有 child 的人。
dict[1] = [[2,3], 2] #the first one is the children list, the second one is the level in the family tree
newDict = {}
subtree = findSub(dict, 2, 0, newDict)
#my newDict is an empty dictionary, newDict= {}
#level stores the person's level in the tree
def findSub(dict, parent, level, newDict):
level += 1
children = dict[parent][0]
if (len(children) == 0):
info = [dict[parent][0], level]
newDict[parent] = info
else:
for child in children:
findSub(dict, child, level, newDict)
return newDict
最佳答案
However, I don't know why the new dictionary of my recursive function can only store those people that have no child.
def findSub(dict, parent, level, newDict):
level += 1
children = dict[parent][0]
if (len(children) == 0):
^^^^^^^^^^^^^^^^^^^^^^^^
info = [dict[parent][0], level]
.....
此 if
检查该元素是否没有子元素。如果它有子元素,您将进一步递归,但在进一步递归之前不会添加该元素。
如果你想保存甚至 parent (最终将导致整个子树),你会做类似的事情
def findSub(dict, parent, level, newDict):
level += 1
children = dict[parent][0]
info = [dict[parent][0], level]
newDict[parent] = info
if (len(children) != 0):
for child in children:
findSub(dict, child, level, newDict)
return newDict
关于Python递归查找 parent 的儿子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445063/