你描述的是一棵完整的树:这样一棵树的叶子都在同一层次。
您可以使用 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)。