java 求二叉树中节点的最大距离.

12 篇文章 0 订阅
11 篇文章 0 订阅
如果我们把二叉树看成一个图,
  父子节点之间的连线看成是双向的,
  我们姑且定义"距离"为两节点之间边的个数。
  写一个程序,

  求一棵二叉树中相距最远的两个节点之间的距离


public class MaxDistance {
	static int  MaxLen=0;
	
	public void FindMaxLen(Node pRoot){
		if(pRoot==null){
			return;
		}
		if(pRoot.pLeft==null){
			pRoot.MaxLeft=0;
		}
		if(pRoot.pRight==null){
			pRoot.MaxRight=0;
		}
		if(pRoot.pLeft!=null){
			FindMaxLen(pRoot.pLeft);
		}
		if(pRoot.pRight!=null){
			FindMaxLen(pRoot.pRight);
		}
		if(pRoot.pLeft!=null){
			int nTempMax=0;
			nTempMax=pRoot.pLeft.MaxLeft>pRoot.pLeft.MaxRight?pRoot.pLeft.MaxLeft:pRoot.pLeft.MaxRight;
			pRoot.MaxLeft=nTempMax+1;
		}
		if(pRoot.pRight!=null){
			int nTempMax=0;
			nTempMax=pRoot.pRight.MaxLeft>pRoot.pRight.MaxRight?pRoot.pRight.MaxLeft:pRoot.pRight.MaxRight;
			pRoot.MaxRight=nTempMax+1;
		}
		if(pRoot.MaxLeft+pRoot.MaxRight>MaxLen){
			MaxLen=pRoot.MaxLeft+pRoot.MaxRight;
		}
	}
	public static void main(String[] args) {
		Node root=new Node(0);
		Node p1=new Node(1);
		Node p2=new Node(2);
		Node p3=new Node(3);
		Node p4=new Node(4);
		Node p5=new Node(5);
		Node p6=new Node(6);
		Node p7=new Node(7);
		Node p8=new Node(8);
		root.pLeft=p1;
		root.pRight=p2;
		p1.pLeft=p3;
		p3.pLeft=p4;
		p2.pLeft=p5;
		p2.pRight=p6;
		p6.pRight=p7;
		p7.pRight=p8;
		System.out.println(MaxLen);
		new MaxDistance().FindMaxLen(root);
		System.out.println(MaxLen);
	}
}
 class Node{
	 Node pLeft;
	 Node pRight;
	 int MaxLeft;
	 int MaxRight;
	 int data;
	 public Node(int data){
		 this.data=data;
	 }
 }
树  

     

结果:7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值