[英]Calculating node depths of all nodes in a Binary Tree
我正在嘗試解決來自 Algoexpert的節點深度問題。 該問題要求您計算給定二叉樹中所有節點的深度總和。 例如,給定這棵樹 -
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
總和應該是 16。
我為它寫了一個遞歸解決方案,我認為這是正確的,但有趣的是,只有第一個測試通過,而其余的測試用例失敗。 這是我的解決方案-
import java.util.*;
class Program {
// static variable to hold the final sum
private static int finalSum = 0;
public static int nodeDepths(BinaryTree root) {
// Write your code here.
int runningSum = 0;
depthHelper(root.left, runningSum);
depthHelper(root.right, runningSum);
return finalSum;
}
private static void depthHelper(BinaryTree node, int runningSum) {
if(node == null) return;
runningSum++;
finalSum += runningSum;
depthHelper(node.left, runningSum);
depthHelper(node.right, runningSum);
}
static class BinaryTree {
int value;
BinaryTree left;
BinaryTree right;
public BinaryTree(int value) {
this.value = value;
left = null;
right = null;
}
}
}
算法本身相當簡單。
有一個runningSum
變量(初始化為 -1 以說明根),每次我訪問一個新節點(即:從它的父節點向下一級)時,我都會向其中添加 1。 並且,這個runningSum
變量的值在每次遞歸調用時添加到finalSum
變量中。
例如,在節點 2 處, runningSum
為1
,並將其添加到finalSum
為0
。 現在finalSum
變為1
。 節點3
相同,之后finalSum
變為2
。 在節點4
, runningSum
變為2
, finalSum
變為4
。
第一個測試用例通過了,我收到了這條消息——
但是,隨后的所有案例都失敗了。 我認為可能發生的情況是- 前一個測試用例執行的輸出沒有被清除,並且以某種方式被添加到當前測試用例執行的結果中。
這就是為什么我認為這可能是原因 -
1. Test case 2 - our code output - 0, your code output - 16
2. Test case 3 - our code output - 1, your code output - 17
3. Test case 4 - our code output - 2, your code output - 19
4. Test case 5 - our code output - 4, your code output - 23
5. Test case 6 - our code output - 21, your code output - 44
6. Test case 7 - our code output - 42, your code output - 86
請注意上次執行的結果如何不被清除並被添加到后續執行的“我們的代碼輸出”中。 例如,在第二個測試用例中,“您的代碼輸出”結果顯示16
,這實際上是第一個測試用例的結果。
這是由於在代碼中使用了全局static
變量嗎? 但是我在 Leetcode 上多次使用相同的方法,並且在那里運行良好。
還是我的算法中存在不同的錯誤?
PS - 我知道在這里使用屏幕截圖是不受歡迎的,但有可能這是一個特定於平台的問題,所以我不得不使用它。
在我看來,發生這種行為並不是錯誤。 這是因為一切都靜止了。 有很多可能性可以避免這個問題。 其中兩個解釋如下:
使用靜態方法但使用無狀態類:
public static int nodeDepths(BinaryTree root) {
// Write your code here.
return depthHelper(root.left, 1) + depthHelper(root.right, 1);
}
private static int depthHelper(BinaryTree node, int sum) {
if (node == null) return 0;
return sum + depthHelper(node.left, sum + 1) + depthHelper(node.right, sum + 1);
}
創建一個對象(如果您不只對對象執行一項操作,則變得更有用):
public static int nodeDepths(BinaryTree root) {
// Write your code here.
return new Program().depthSum(root); // call to non-static method
// like this you can use your original implementation, but the
// class variable (finalSum) has to be non-static too
}
這兩種實現都是線程安全的。
看起來他們的測試平台使用您的類的一個對象運行測試。 所以你應該在nodeDepths()
方法結束時清除finalSum
:
public static int nodeDepths(BinaryTree root) {
// Write your code here.
int runningSum = 0;
depthHelper(root.left, runningSum);
depthHelper(root.right, runningSum);
int temp=finalSum;
finalsum=0;
return temp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.