【发布时间】: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