在 Python 中查找同一层级叶子节点数据之和的乘积
假设我们有一棵二叉树。我们需要执行以下操作:
对于每一层,如果该层存在叶子节点,则找到所有叶子节点的和。否则忽略。
找到所有这些和的乘积并返回。
因此,如果输入如下所示:
则输出将为 270。前两层没有叶子节点。第三层只有一个叶子节点 9。最后一层有四个叶子节点 2、12、5 和 11。所以结果是 9 * (2 + 12 + 5 + 11) = 270
为了解决这个问题,我们将遵循以下步骤:
如果根节点为空,则
返回 0
res := 1
que := 一个队列
将根节点插入队列的末尾
无限循环:
no_of_nodes := 队列的大小
如果 no_of_nodes 等于 0,则
退出循环
sum_level := 0
found_leaf := False
当 no_of_nodes > 0 时,执行:
curr_node := 队列的第一个元素
如果 curr_node 是叶子节点,则
found_leaf := True
sum_level := sum_level + curr_node.data
从队列中删除第一个元素
如果 curr_node.left 不为空,则
将 curr_node.left 插入队列的末尾
如果 curr_node.right 不为空,则
将 curr_node.right 插入队列的末尾
no_of_nodes := no_of_nodes - 1
如果 found_leaf 为真,则
res := res * sum_level
返回 res
示例
让我们来看下面的实现,以便更好地理解:
class TreeNode: def __init__(self, data): self.data = data self.left = self.right = None def isLeaf(root) : return (not root.left and not root.right) def find_res(root) : if (not root) : return 0 res = 1 que = [] que.append(root) while (True): no_of_nodes = len(que) if (no_of_nodes == 0) : break sum_level = 0 found_leaf = False while (no_of_nodes > 0) : curr_node = que[0] if (isLeaf(curr_node)) : found_leaf = True sum_level += curr_node.data que.pop(0) if (curr_node.left != None) : que.append(curr_node.left) if (curr_node.right != None) : que.append(curr_node.right) no_of_nodes -=1 if (found_leaf) : res *= sum_level return res root = TreeNode(8) root.left = TreeNode(8) root.right = TreeNode(6) root.left.right = TreeNode(7) root.left.left = TreeNode(9) root.left.right.left = TreeNode(2) root.left.right.right = TreeNode(12) root.right.right = TreeNode(10) root.right.right.left = TreeNode(5) root.right.right.right = TreeNode(11) print(find_res(root))
输入
root = TreeNode(8) root.left = TreeNode(8) root.right = TreeNode(6) root.left.right = TreeNode(7) root.left.left = TreeNode(9) root.left.right.left = TreeNode(2) root.left.right.right = TreeNode(12) root.right.right = TreeNode(10) root.right.right.left = TreeNode(5) root.right.right.right = TreeNode(11)
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
270