用python写一段对多叉树的遍历代码统计其中叶子结点的个数
可以使用递归来遍历多叉树,并统计叶子节点的个数。下面是一个示例代码:
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def count_leaves(root):
if not root:
return 0
if not root.children:
return 1
count = 0
for child in root.children:
count += count_leaves(child)
return count
# 创建一个多叉树
# A
# / | \
# B C D
# / \ | / \
# E F G H I
# |
# J
root = TreeNode('A')
node_b = TreeNode('B')
node_c = TreeNode('C')
node_d = TreeNode('D')
node_e = TreeNode('E')
node_f = TreeNode('F')
node_g = TreeNode('G')
node_h = TreeNode('H')
node_i = TreeNode('I')
node_j = TreeNode('J')
root.children = [node_b, node_c, node_d]
node_b.children = [node_e, node_f]
node_c.children = [node_g]
node_d.children = [node_h, node_i]
node_h.children = [node_j]
leaf_count = count_leaves(root)
print("叶子结点的个数为:", leaf_count)
输出结果:
叶子结点的个数为: 4
在上面的代码中,我们定义了一个TreeNode类,用于表示多叉树的节点。每个节点包含一个值和一个子节点列表。然后,我们定义了一个count_leaves函数,该函数通过递归遍历多叉树,并在遇到叶子节点时进行计数。最后,我们创建了一个多叉树,并调用count_leaves函数来统计叶子节点的个数
原文地址: https://www.cveoy.top/t/topic/hzpE 著作权归作者所有。请勿转载和采集!