您的位置:首页 > 编程语言

编程之美笔记 3.8 求二叉树中节点的最大距离

2011-10-02 13:16 288 查看
java实现,调试通过。

以下代码已经调试通过,其中涉及到一些细节的注释,是自己在写程序出现错误的地方!

尤其是getMaximunDistance()方法中做的注释对自己还是很有利的,即使用递归方法时,做退出的情况,我一开始分成了多种情况,root.lchild和root.rchild是否为null,这样要分几种情况,反而复杂了,其实用这一种情况就很好,但是要返回的info对象不能为空。

import java.util.Scanner;

class Tode1 {
int data;
Tode1 lchild;
Tode1 rchild;

Tode1(int a) {
data = a;
lchild = null;
rchild = null;
}
}

class Info{
int TreeMaxDistanceNodes;
int TreeMaxDepth;
}

public class DistanceBetweenTwoNodes {

static Tode1 root = null;

static Tode1 creatTree(Tode1 root) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
if (a == 0) {
return null;
}

else {
root = new Tode1(a);
root.lchild = creatTree(root.lchild);
root.rchild = creatTree(root.rchild);
return root;
}
}

static void printInOrder(Tode1 root) {
if (root == null)
return;
else {
System.out.println(root.data);
printInOrder(root.lchild);
printInOrder(root.rchild);
}

}

static Info getMaximunDistance(Tode1 root){
if(root==null) {//我一开始分成了多种情况,
//root.lchild和root.rchild是否为null,这样要分几种情况,反而复杂了
//其实用这一种情况就很好,但是要返回的info对象不能为空。
Info info=new Info();
info.TreeMaxDepth=-1;//必须写成-1,因为还需要每个节点加1,空节点当成节点加1的话,必须是-1,才能可以啊。
info.TreeMaxDistanceNodes=0;//写成-1肯定不对

return info;
}
else{

Info infoleft=getMaximunDistance(root.lchild);
Info inforight=getMaximunDistance(root.rchild);
Info info=new Info();

int templchildmaxDepth=infoleft.TreeMaxDepth;
int temprchildmaxDepth=inforight.TreeMaxDepth;

int templchildmaxDistanceNodes=infoleft.TreeMaxDistanceNodes;
int temprchildmaxDistanceNodes=inforight.TreeMaxDistanceNodes;

int BiggerDistance=0;

if(templchildmaxDepth>temprchildmaxDepth){
info.TreeMaxDepth=templchildmaxDepth+1;
}
else
info.TreeMaxDepth=temprchildmaxDepth+1;

int tempMaxDistanceNodes=temprchildmaxDepth+templchildmaxDepth+2;
if(templchildmaxDistanceNodes>temprchildmaxDistanceNodes)
BiggerDistance=templchildmaxDistanceNodes;
else
BiggerDistance=temprchildmaxDistanceNodes;

if(BiggerDistance>tempMaxDistanceNodes)
info.TreeMaxDistanceNodes=BiggerDistance;
else
info.TreeMaxDistanceNodes=tempMaxDistanceNodes;

return info;
}

}

public static void main(String[] args) {
// TODO Auto-generated method stub

Tode1 tree1 = creatTree(root);
printInOrder(tree1);//必须用返回的tree1才行,这个tree1才真正是发生变化的树,如果用root肯定不对。
System.out.print(getMaximunDistance(tree1).TreeMaxDepth);
System.out.print(getMaximunDistance(tree1).TreeMaxDistanceNodes);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 java tree null class