【问题标题】:how to create a tree data structure by user defined tree level and child in python?如何在 python 中通过用户定义的树级别和子级创建树数据结构?
【发布时间】:2021-03-01 09:00:02
【问题描述】:

我想创建树数据结构,用户应该在其中定义树的级别和树的子节点。 所以如果我的输入是 2 而子输入是 2 那么输出应该是

    A
   / \
  B   C
 / \  / \
D   E F  G

数据可能是任何东西..

【问题讨论】:

  • "data可能是anyting":但如果用户只提供heightnumber of children,那么在哪里数据来自哪里?
  • 数据来自用户输入。如果孩子的数量是 3,那么用户可以像 [A,B,C] 一样输入 3 次。并且孩子的数据应该是 A B C

标签: python-3.x data-structures tree


【解决方案1】:

你描述的是一棵完整的树:这样一棵树的叶子都在同一层次。

您可以使用 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 表示树中的 number 个级别,在本例中为 3(而不是您的问题中的 2)。

【讨论】:

  • 你能给这个答案一些反馈吗?
  • 非常感谢...我如何在树中插入数据作为用户输入,例如如果 childcount 为 2,那么用户可以输入 2 个数据,如 [head,tail] 并且用户可以输入概率像概率树这样的数据..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多