代码之家  ›  专栏  ›  技术社区  ›  adapap

非二叉树递归

  •  0
  • adapap  · 技术社区  · 8 年前

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

    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)
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Michael Butscher    8 年前

    如果在类中编写变量,就像在

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

    它们绑定到类,而不是实例。对于 value __init__ 构造函数,但引用的列表 children 被所有人共享 Tree 实例。

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

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