这是一个使用Python实现的通用非二叉树的示例代码:
class TreeNode:
def __init__(self, val):
self.val = val
self.children = []
def build_tree(nodes):
if not nodes:
return None
root = TreeNode(nodes[0])
stack = [root]
idx = 1 # 用于遍历 nodes 列表
while stack and idx < len(nodes):
node = stack.pop()
num_children = nodes[idx] # 获取当前节点的子节点数量
for i in range(num_children):
child = TreeNode(nodes[idx + i + 1])
node.children.append(child)
stack.append(child)
idx += num_children + 1
return root
def print_tree(root):
if not root:
return
queue = [root]
while queue:
node = queue.pop(0)
print(node.val, end=' ')
for child in node.children:
queue.append(child)
nodes = [1, 3, 2, 2, 5, 6, 4, 8, 9]
root = build_tree(nodes)
print_tree(root)
在这个示例中,我们定义了一个TreeNode类来表示通用非二叉树的节点。每个节点包含一个值和一个子节点列表。build_tree函数接受一个节点值列表,并使用迭代的方式构建通用非二叉树。print_tree函数用于按层级打印树的节点值。
在示例中,我们使用节点值列表[1, 3, 2, 2, 5, 6, 4, 8, 9]来构建一个通用非二叉树,并打印出节点值。输出结果为:1 3 2 2 5 6 4 8 9。
你可以根据自己的需求修改节点值列表来构建不同形状和层级的通用非二叉树。
下一篇:不同层级上按组数据的聚合差异