问:二叉树中查找最大距离节点的程序。

2025年3月17日 | 阅读16分钟

说明

在此程序中,我们需要找出二叉树中距离最大的节点。根据我们的方法,树中所有节点之间的所有距离都将存储在变量 distance 中。使用变量 MaxDistance 来存储最大值。最初,MaxDistance 初始化为 distance 的值。如果找到任何大于 MaxDistance 的值,则覆盖 MaxDistance 的值。

重复此过程,直到找到树中两个节点之间可能的最大距离。过程的算法如下。

Program to find the nodes which are at the maximum distance in a Binary Tree

算法

  1. 定义 Node 类,它有三个属性:data、leftright。其中,left 表示节点的左子节点,right 表示节点的右子节点。
  2. 创建节点时,将数据传递给节点的 data 属性,并将 left 和 right 都设置为 null
  3. 定义另一个具有两个属性 root 和 treeArray 的类。
    1. Root 表示树的根节点,并将其初始化为 null。
    2. treeArray 将存储二叉树的数组表示。
  4. nodesAtMaxDistance() 函数将找出位于最大距离处的节点。
    1. 它将计算二叉树中所有节点之间的距离,并将其存储在变量 distance 中。
    2. MaxDistance 用于跟踪节点之间的最大可能距离。如果 maxDistance 小于 distance,则 distance 的值将存储在 maxDistance 中。清除数组以清除先前存储的值。位于最大距离处的节点将存储在数组 arr 中。
    3. 如果多个节点对位于最大距离处,则将它们存储在数组 arr 中。
  5. calculateSize() 将计算树中的节点数。
  6. convertBTtoArray() 函数将通过遍历树并将元素添加到 treeArray 来把二叉树转换为其数组表示。
  7. getDistance() 函数将计算给定节点到根的距离。
  8. LowestCommonAncestor() 函数将找出节点 n1 和 n2 的最近公共祖先。
    1. 如果其中一个节点等于根节点,则返回根节点作为最近公共祖先。
    2. 否则,在左子树和右子树中搜索节点 n1 和 n2。
    3. 如果找到一个节点,该节点的左子节点是 n1,右子节点是 n2,反之亦然。则返回该节点作为最近公共祖先。
  9. FindDistance() 函数将计算两个节点之间的距离。
    1. 首先,它计算每个节点到根节点的距离。
    2. 从该根节点中减去 2 * 最近公共祖先的距离。

解决方案

Python

输出

Nodes which are at maximum distance: 
( 4,9 )
( 5,9 )

C

输出

Nodes which are at maximum distance: 
( 4,9 )
( 5,9 )

JAVA

输出

Nodes which are at maximum distance: 
( 4,9 )
( 5,9 )

C#

输出

Nodes which are at maximum distance: 
( 4,9 )
( 5,9 )

PHP

输出

Nodes which are at maximum distance: 
( 4,9 )
( 5,9 )
 
下一个主题程序列表