如何解决如何在python中通过用户定义的树级别和子项创建树数据结构?
我想制作树数据结构,用户应该在其中定义树的级别和树的子级。 所以如果我的输入是 2 而子输入是 2 那么输出应该是
A
/ \
B C
/ \ / \
D E F G
数据可能是任何东西..
解决方法
你描述的是一棵完整的树:这种树的叶子都在同一层。
您可以使用 BFS 或 DFS 算法执行此操作。由于我不知道您将从何处获取数据,因此我在这里仅使用随机数作为节点值。此代码使用递归 DFS 算法:
from random import randrange
class Node:
def __init__(self,value,children=None):
self.value = value
self.children = children or []
# helper function to allow a quick view on the tree structure
def tolist(self):
if self.children:
return [self.value,[child.tolist() for child in self.children]]
return self.value
def fulltree(height,childcount):
if height == 0:
return None
if height == 1: # Leaf node
return Node(randrange(1000))
# Recursion:
return Node(randrange(1000),[fulltree(height-1,childcount)
for _ in range(childcount)])
您可以按如下方式运行它:
tree = fulltree(3,2) # A tree with height 3 and 2 children per internal node
print(tree.tolist())
这输出类似:
[789,[[200,[196,455]],[616,[32,951]]]]
请注意,这里的 height 表示树中的层数,在本例中为 3(而不是您问题中的 2)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。