我实际上正在学习如何应用递归来解决一些现实生活中的问题。比方说,我有一本存储家谱树的字典,每个人的 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 检查元素是否没有子元素。如果它有子元素,您将进一步递归,但在进一步递归之前不添加该元素。
如果你甚至想保存父节点(这最终会导致整个子树),你会做类似的事情
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
