【发布时间】: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 是唯一的。在示例中每个出现两次。但是,如果我从多个根开始,我想我有一个图表。