【问题标题】:Python recursive function to create generic treePython递归函数创建通用树
【发布时间】:2020-05-30 13:12:39
【问题描述】:

我正在尝试为每个节点创建一个包含 n 个子节点的树。 问题是,当我尝试使用递归函数来实现这一点时,我最终会得到多个递归调用,所以我不能有一个 return 语句,因此最终结果是 None

这是我的一段代码:

def recursive_func(tree, n):
    if n == 0:
        return tree
    else:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)
            tree.addChild(child_tree)

get_permutations() 给出要创建的子树列表。我还有一个 Tree 类,其中包含一个节点值和一个子项列表。

这是 Tree 类:

class Tree:
    def __init__(self, result):
        self.node = node
        self.children = []

    def addChild(self, tree):
        self.children.append(tree)

这可能是我的问题设计中的一个菜鸟错误,但我很乐意得到一些帮助。

【问题讨论】:

  • tree.add的返回类型是什么??
  • 你说I ends up with multiple recursive calls你能告诉我们输出吗?也不必说这可能是一个菜鸟错误,没有人会生气,大多数人不会生气,如果您发布格式正确的内容!
  • tree.addChild() 什么都不返回,它只是将孩子附加到树上。我用 Tree 类更新了我的帖子。至于提到多次递归调用,只是因为我在递归调用中有一个for循环。
  • 你为什么不直接使用 multiple return 语句或者在末尾添加一个 return(并删除第一个分支)?对于所有当前分支,该函数似乎应该始终为return tree
  • 好吧,看起来它可以工作@MisterMiyagi!但我仍然不明白为什么,因为我不需要recursive_func() 在最后返回一些东西,所以我认为n == 0 条件中的return 语句足以让递归函数遍历整个树。不过,看来我还是需要return tree,对吧?

标签: python-3.x recursion tree


【解决方案1】:

TLDR:由于您使用recursive_func 的结果,它应该始终returntree


recursive_func对于这个问题有三个重点:

def recursive_func(tree, n):
    if n == 0:
        return tree  # 1.
    else:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)  # 2.
            tree.addChild(child_tree)
    # 3.

现在,1. 定义函数有时 返回一个Tree。这匹配2.总是希望函数返回一个Tree。但是,两者都与3. 冲突,后者在第二个分支完成时隐式返回None

由于除return 之外的第一个分支是空的,因此1.3. 都可以折叠到一个总是返回Tree 的路径。

def recursive_func(tree, n):
    if n > 0:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)
            tree.addChild(child_tree)
    return tree

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多