Python递归地查找父对象的子对象
我实际上正在学习如何应用递归来解决一些现实生活中的问题。比如说,我有一本字典,它存储了一个家谱,每个人的孩子都会存储在这本字典中,它的级别也会存储在这棵树中。我想找出一个家庭的子树,并将其存储到单独的字典中,因此我必须不断检查此人是否有子女。然而,我不知道为什么我的递归函数的新字典只能存储那些没有孩子的人Python递归地查找父对象的子对象,python,dictionary,recursion,Python,Dictionary,Recursion,我实际上正在学习如何应用递归来解决一些现实生活中的问题。比如说,我有一本字典,它存储了一个家谱,每个人的孩子都会存储在这本字典中,它的级别也会存储在这棵树中。我想找出一个家庭的子树,并将其存储到单独的字典中,因此我必须不断检查此人是否有子女。然而,我不知道为什么我的递归函数的新字典只能存储那些没有孩子的人 dict[1] = [[2,3], 2] #the first one is the children list, the second one is the level in the fam
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
然而,我不知道为什么我的递归函数的新字典只能存储那些没有孩子的人
此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
你可能想用这个:哦,它工作得很好。我真的很想知道如何才能掌握递归函数的概念。帮助我的是学习堆栈及其机制(函数如何放在堆栈上,然后在执行后从堆栈中移除):
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