写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这棵二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率
这是2015阿里秋招的一个在线笔试题
实现方法很简单,遍历一遍二叉树,找出最大最小,一相减就可以求出最大的差值
我把之前写的篇Java的二叉树http://blog.youkuaiyun.com/xyz5354/article/details/25003317改了一下
改成
其实就是加了一个整数值进去
之前写了很多的遍历方法
之前在做题的时候居然写递归的方法求值,后面测试了一下,果然结果不对
只要是非递归的的方法遍历都可以很容易找出最大值最小值,效率也比较高,时间复杂度为O(n)
/**
* 按层遍历二叉树
* 2014-5-4
*
* @author:5354xyz
*/
public void levelTraverse(BinaryTree bTree)
{
int max = bTree.intvalue;
int min = bTree.intvalue;
if(bTree == null )
return;
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
queue.offer(bTree);
while(!queue.isEmpty())
{
BinaryTree pNode = queue.poll();
if (pNode.intvalue > max )
max = pNode.intvalue;
if (pNode.intvalue < min)
min = pNode.intvalue;
onVisitListener.visit(pNode); // 访问节点
if(pNode.leftchild != null)
queue.offer(pNode.leftchild);
if(pNode.rightchild != null)
queue.offer(pNode.rightchild);
}
System.out.println("最大差值为:"+max +" - "+min+" = "+(max - min));
return;
}
输出结果: