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

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

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


解题思路:

对于任意一个节点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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值