【问题标题】:How to build a dynamic tree of arbitrary depth in python?如何在python中构建任意深度的动态树?
【发布时间】:2020-02-25 22:16:17
【问题描述】:

我需要构建一棵树,其中每个级别有 n 个子级和 t 个级别。每个节点都会包含一个值。

我可以使用 节点类 制作一棵树,然后对多个级别使用多个 for 循环。但是如何在没有 for 循环的情况下实现这一点(如何递归地做到这一点)?

我认为我在使用递归时犯了一些明显的错误。我从一个节点(根)和一些子节点开始,然后执行以下操作:

class Tree():
   def __init__(self):
     self.children = []
     self.data = []

   def create_children(self, childNum):
     for num in range(childNum):
        self.children.append(Tree())

   def create_data(self, data):
        for val in data:
           self.data.append(val)

root = Tree()  # create root
root.create_data([0])
root.create_children(3)  # create branch 1 with n=3 children

for b1child in root.children:
   b1child.create_data([2]) # create data of each node
   # create branch 2 
   b1child.create_children(3) # create 3 children at each node

   for b2child in b1child.children:
      b2child.create_data([2])         # create branch 3
      b2child.create_children(3)

      for b3child in b2child.children:
        b3child.create_data([2])

# test children exists with value 
root.children[0].children[1].children[2].data

【问题讨论】:

  • 新创建的子节点在创建时会得到什么值?
  • 值应该来自另一个函数

标签: python-3.x tree


【解决方案1】:

Node 类中使用递归方法最容易做到这一点。像这样的东西,虽然你需要添加一些东西来为每个 Node 实例提供一个值:

class Node:
    def __init__(self):
        self.children = []

    def create_children(self, num_children, depth):
        if depth == 0:                                     # base case
            return

        for i in range(num_children):
            child = Node()
            self.children.append(child)
            child.create_children(num_children, depth-1)   # recurse!

然后您的Tree 代码可以创建根节点并调用root.create_children(n, t)(或者可能是t-1,我不确定根是否应计入深度)。

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多