【问题标题】:Non-binary tree recursion非二叉树递归
【发布时间】:2017-12-19 21:32:41
【问题描述】:

我正在尝试制作一个程序来设置一个非二叉树,每个节点都连接到子节点。在这个测试示例中,为了简单起见,我使用了二叉树。输入是这样的:

1
3   5
4   6

(数字之间使用制表符)。 我正在尝试从根 (1) 开始生成树,其子节点为 3 和 5,并且每个节点都有子节点 4 和 6。 树形图可能如下所示:

    4
   /
  3
 / \
1   6
 \ /
  5
   \
    4

当我尝试将孩子添加到我的树时,它会创建一个无限循环来调用我的递归函数。我已经将问题缩小到它在循环中调用分支为 1 的函数,但这里是代码:

# input is a list of branch values
file = open("treehash.txt","r")
input = file.readlines()
for line in range(len(input)):
input[line] = input[line].rstrip().split('\t')
file.close()

# create the tree node
class Tree(object):
    value = None
    children = []
    def __init__(self, value):
        self.value = value

# adds all children to a given parent
def set_children(parent, branch):
    if branch < len(input) - 1:
        for num in input[branch + 1]:
            parent.children.append(Tree(int(num)))
        for child in parent.children:
            set_children(child, branch + 1)

# store all roots in array
roots = []
for root in range(len(input[0])):
    roots.append(Tree(int(input[0][root])))
    set_children(roots[root], 0)

【问题讨论】:

  • 如果 4 和 6 有多个父级,则您有一个图表,而不是一棵树。
  • 4 和 6 对 3 和 5 是唯一的。在示例中每个出现两次。但是,如果我从多个根开始,我想我有一个图表。

标签: python recursion tree


【解决方案1】:

如果你像在类中那样编写变量

class Tree(object):
    value = None
    children = []

它们绑定到类,而不是实例。对于value,您在__init__ 构造函数中使用实例绑定变量覆盖它,但children 引用的列表由所有Tree 实例共享。

删除以上变量设置并改用:

class Tree(object):
    def __init__(self, value):
        self.value = value
        self.children = []

【讨论】:

    猜你喜欢
    • 2016-04-19
    • 2014-03-29
    • 2010-12-07
    • 2020-09-15
    • 1970-01-01
    • 2013-04-21
    • 2023-04-10
    • 1970-01-01
    • 2011-05-08
    相关资源
    最近更新 更多