问:二叉树所有节点求和程序

17 Mar 2025 | 6 分钟阅读

说明

在此程序中,我们需要计算二叉树中存在的节点的总和。首先,我们将遍历左子树并计算左子树中存在的节点的总和。类似地,我们计算右子树中存在的节点的总和,并通过添加根节点的数据来计算总和。

Program to find the sum of all the nodes of a Binary Tree

对于给定的树,二叉树节点的总和将是 1 + 2 + 5 + 8 + 6 + 9 = 31。

算法

  1. 定义 Node 类,该类包含三个属性:data、left 和 right。这里,left 表示节点的左子节点,right 表示节点的右子节点。
  2. 创建节点时,数据将传递到节点的 data 属性,left 和 right 都将设置为 null。
  3. 定义另一个类,该类有一个 root 属性。
    1. 表示树的根节点,并将其初始化为 null。
  4. calculateSum() 将计算二叉树中存在的节点的总和
    1. 它检查 root 是否为空,这意味着树为空。
    2. 如果树不为空,则遍历左子树,计算节点总和并将其存储在 sumLeft 中。
    3. 然后,遍历右子树,计算节点总和并将其存储在 sumRight 中。
    4. 最后,计算总和 = temp.data + sumLeft + sumRight。

解决方案

Python

输出

Sum of all nodes of binary tree: 31

C

输出

Sum of all nodes of binary tree: 31

JAVA

输出

Sum of all nodes of binary tree: 31

C#

输出

Sum of all nodes of binary tree: 31

PHP

输出

Sum of all nodes of binary tree: 31
 
下一个主题程序列表