寫一個函數,輸入一個二叉樹,樹中每個節點存放了一個整數值,函數返回這棵二叉樹中相差最大的兩個節點間的差值絕對值。請注意程序效率
這是2015阿里秋招的一個在線筆試題
實現方法很簡單,遍歷一遍二叉樹,找出最大最小,一相減就可以求出最大的差值
我把之前寫的篇Java的二叉樹http://blog.csdn.net/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;
}
輸出結果: