我试图制作一个程序,建立一个非二叉树,每个节点都连接到子节点。在这个测试示例中,为了简单起见,我使用了二叉树。输入如下:
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)