编程之美笔记 3.8 求二叉树中节点的最大距离(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); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值