這兩個版本之間有什麼區別?計算樹中的兩個版本離開樹
public static int countLeaves(IntTreeNode root) {
if (root == null) {
return 0;
} else
return 1 + countLeaves(root.left) + countLeaves(root.right);
}
public static int countLeaves(IntTreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null) {
return 1;
} else
return countLeaves(root.left) + countLeaves(root.right);
}
我在互聯網上找不到任何使用第一個版本的東西。 第一個版本是否錯誤?
我試圖在紙上描繪它們,它們看起來是一樣的。 但我只想確定一下。
當您運行它時,第一個版本是否會提供正確的結果? – ChiefTwoPencils
@ChiefTwoPencils我測試了幾個案例,是的。 – chuck
我不認爲他們可以給出相同的結果。 – ChiefTwoPencils