以下是一个用于计算玫瑰树中元素数量的函数的示例代码:
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def count_elements(root):
if root is None:
return 0
count = 1
for child in root.children:
count += count_elements(child)
return count
# 创建一个玫瑰树
root = TreeNode(1)
child1 = TreeNode(2)
child2 = TreeNode(3)
child3 = TreeNode(4)
child4 = TreeNode(5)
child5 = TreeNode(6)
root.children.append(child1)
root.children.append(child2)
child1.children.append(child3)
child1.children.append(child4)
child2.children.append(child5)
# 计算玫瑰树中元素的数量
element_count = count_elements(root)
print("玫瑰树中元素的数量为:", element_count)
在这个示例中,我们定义了一个TreeNode
类来表示树的节点。每个节点有一个value
属性表示节点的值,以及一个children
属性表示该节点的子节点列表。
然后,我们定义了一个count_elements
函数,该函数使用递归方式计算玫瑰树中元素的数量。如果根节点为空,表示玫瑰树是空的,元素数量为0。否则,我们将当前节点计数为1,并递归计算每个子节点的元素数量,并将它们累加到计数中。
最后,我们创建了一个玫瑰树的示例,并调用count_elements
函数来计算元素的数量,并打印结果。