如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
解题思路:
对于任意一个节点p,以它为根节点的二叉树中最远的距离是:
Max(p->leftNode.height+1+p->rightNode.height+1,maxDistance(p->leftNode),maxDistance(p->rightNode));
即对于p来说,它添加进二叉树对最远距离造成的影响就是它在左子树中的高度加上它在右子树中的高度,然后与原有的最远距离(左子树中的最远距离,右子树中的最远距离)相比即可得到结果
package com;
public class Q11 {
static int max = 0;
public static Node init()
{
Node a = new Node('a');
Node b = new Node('a');
Node c = new Node('a');
Node d = new Node('a');
Node e = new Node('a');
Node f = new Node('a');
Node g = new Node('a');
Node h = new Node('a');
Node i = new Node('a');
Node j = new Node('a');
a.leftChild = b;
//a.RightChild = c;
b.leftChild = d;
d.RightChild = e;
c.leftChild = f;
c.RightChild = g;
d.leftChild = h;
f.RightChild = i;
i.leftChild = j;
return a;
}
public static int getMaxLength(Node node) //递归主体函数,返回该节点作为根节点的子树的高度
{
if(node == null)
return 0;
int llength = 0; //记录左子树的高度
int rlength = 0; //记录右子树的高度
if(node.leftChild != null) //得到该节点在它的左子树中的高度
llength = getMaxLength(node.leftChild)+1;
else
llength = 0;
if(node.RightChild != null) //得到该节点在它的右子树中的高度
rlength = getMaxLength(node.RightChild) +1;
else
rlength = 0;
int sum = llength+rlength; //最远距离经过该节点的时候
if(sum>max) //与当前的max相比
max = sum; //在之前getMaxLength()函数递归调用的时候,max已经与左子树中的最远距离、右子树中的最远距离比较了
return llength>rlength?llength:rlength;
}
public static void main(String[] args) {
Node root = init();
getMaxLength(root);
System.out.println(max);
}
}