写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这棵二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率
这是2015阿里秋招的一个在线笔试题
实现方法很简单,遍历一遍二叉树,找出最大最小,一相减就可以求出最大的差值
只要是非递归的的方法遍历都可以很容易找出最大值最小值,效率也比较高,时间复杂度为O(n)
/**
* 按层遍历二叉树
*/
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;
}