一些作業問題: 我需要檢查二叉樹是否遵循此規則:每個節點有 有數字,我需要檢查這個數字是否大於或等於全部它下面的節點。Java - 如何計算和比較二叉樹
如果所有樹都遵循該規則,該方法應該返回true。 我寫了這個代碼:
public static boolean isSigma(Node n)
{
if (n == null)
return true;
if (n.getLeftSon() == null && n.getRightSon() == null)
return true;
else return n.getNumber() >= sumCalc(n) && isSigma(n.getLeftSon()) && isSigma(n.getRightSon());
}
private static int sumCalc(Node n) // return the sum of specific Node plus other Node/s that are under it
{
if (n==null)
return 0;
else return n.getNumber() + sumCalc(n.getLeftSon()) + sumCalc(n.getRightSon());
}
左樹將返回false,右邊的樹將返回true。
但由於某些原因代碼無法正常工作。 我檢查了幾棵樹,它給我總是假的。 順便說一句,我必須在遞歸方法中編寫它,並且不允許更改公共方法簽名。
我會通過你的代碼一步與導致問題的最簡單的例子一個調試器。這會告訴你你的bug在哪裏。 (這就是工具的用途) – 2012-02-05 15:45:08