二叉樹最大總和水平 - 更好的設計?
我已經編寫了一些代碼來查找二叉樹中的級別,具有最大數量的元素。我有幾個問題:
這是一個好的設計嗎?我已經使用了2個隊列,但兩個隊列存儲的元素總和將小於n。所以我認為應該沒問題。 可以有更好的設計嗎?
public class MaxSumLevel {
public static int findLevel(BinaryTreeNode root) {
Queue mainQ = new Queue();
Queue tempQ = new Queue();
int maxlevel = 0;
int maxVal = 0;
int tempSum = 0;
int tempLevel = 0;
if (root != null) {
mainQ.enqueue(root);
maxlevel = 1;
tempLevel = 1;
maxVal = root.getData();
}
while ( !mainQ.isEmpty()) {
BinaryTreeNode head = (BinaryTreeNode) mainQ.dequeue();
BinaryTreeNode left = head.getLeft();
BinaryTreeNode right = head.getRight();
if (left != null) {
tempQ.enqueue(left);
tempSum = tempSum + left.getData();
}
if (right != null) {
tempQ.enqueue(right);
tempSum = tempSum + right.getData();
}
if (mainQ.isEmpty()) {
mainQ = tempQ;
tempQ = new Queue();
tempLevel ++;
if (tempSum > maxVal) {
maxVal = tempSum;
maxlevel = tempLevel;
tempSum = 0;
}
}
}
return maxlevel;
}
}
最佳答案
我最初的批評是你的方法沒有javadoc註釋,清楚明確地說明了 該方法應該做什麽。 我為什麽這麽說? 好吧,主要是因為你的問題有完全相同的問題!你說:
我編寫了一些代碼,用於在二叉樹中查找具有最大元素數的級別。
這是對你(顯然)試圖做的不好的描述:
單詞“level”通常是指節點與(例如)樹根的距離。但你顯然是指整棵樹的“高度”。 短語“具有最大數量的元素”尚不清楚。你在說什麽?這對這個問題有何影響? (我沒有在代碼中看到元素的最大數量參數...或對此的任何引用。)
那為什麽這很重要?
因為我(讀者)不應該通讀您的代碼來試圖找出您試圖解決的問題。特別是如果你的實現是非顯而易見的......它是......並且可能包含錯誤,這可能會讓我認為它解決了一個與你實際嘗試解決的問題不同的問題。