问答题 如何求二叉树中结点的最大距离
【正确答案】
【答案解析】问题描述:结点的距离是指这两个结点之间边的个数。写一个程序求一棵二叉树中相距最远的两个结点之间的距离。
一般而言,对二叉树的操作通过递归方法实现比较容易。求最大距离的主要思想如下:首先,求左子树距根结点的最大距离,记为leftMaxDistance;其次,求右子树距根结点的最大距离,记为rightMaxDistance,那么二叉树中结点的最大距离maxDistance满足maxDistance=leftMaxDistance+rightMaxDistance。
实现代码如下:
class Node{
public int data;
public Node left;
public Node right;
public int leftMaxDistance; //左子树距根结点的最大距离
public int rightMaxDistance; //右子树距根结点的最大距离
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
public class BinaryTree{
private int maxLen=0;
private int max(int a, int b){
return a>b?a:b;
}
publicvoid FindMaxDistance(Node root){
if(root==null)
return;
if(root.left==null)
root.leftMaxDistance=0;
if(root.right==null)
root.rightMaxDistance=0;
if(root.left!=null)
FindMaxDistance(root.left);
if(root.right !=null)
FindMaxDistance(root.fight);
//计算左子树中距离根结点的最大距离
if(root.left!=null)
root.leftMaxDistanee=max(root.left.leftMaxDistance, root.left.rightMaxDistance)+1;
//计算右子树中距离根结点的最大距离
if(root.right !=null)
root.rightMaxDistance=max(root.right.leftMaxDistance, root.right.rightMaxDistance)+1;
//获取二叉树所有结点的最大距离
if(root.leftMaxDistance+root.rightMaxDistance>maxLen){
maxLen=root.leftMaxDistance+root.rightMaxDistance;
}
}
}