2017-03-25 42 views
1

我需要寫的操作,算誰有兩個兒子是彼此相等的節點。我試過,但我得到錯誤,並不是所有的代碼路徑都返回一個值。 請幫我做個測試 謝謝。計數節點

public static int CountWhoHasTwoSameSons(BinNode<int> Head) 
{ 
     if (Head != null) 
     { 
      if (IsLeaf(Head)) 
       return 1; 

      if ((Head.HasLeft() && Head.HasRight()) && (Head.GetRight() == Head.GetLeft())) 
       return 1 + CountWhoHasTwoSameSons(Head.GetLeft()) + CountWhoHasTwoSameSons(Head.GetRight()); 
     } 

} 

static void Main(string[] args) 
{ 
     BinNode<int> t = new BinNode<int>(3); 
     BinNode<int> t1 = new BinNode<int>(3); 
     BinNode<int> t2 = new BinNode<int>(3); 
     BinNode<int> t3 = new BinNode<int>(3); 
     BinNode<int> t4 = new BinNode<int>(t,3,t1); 
     BinNode<int> t5 = new BinNode<int>(t2,3,t3); 
     BinNode<int> t6 = new BinNode<int>(t4,3,null); 
     BinNode<int> Head = new BinNode<int>(t6,3,t5); 
     Console.WriteLine(SumTree(Head)); 
     Console.WriteLine(LeafCounter(Head)); 
     Console.WriteLine(CountWhoHasTwoSameSons(Head)); 

     Console.ReadLine(); 
} 

回答

0

由於您的錯誤狀態,您的當前函數在某些情況下可能沒有返回語句。

public static int CountWhoHasTwoSameSons(BinNode<int> Head) 
{ 
     if (Head == null) 
      return 0; 
     if (IsLeaf(Head)) 
      return 1; 
     if ((Head.HasLeft() && Head.HasRight()) && 
      (Head.GetRight() == Head.GetLeft())) // It happens with this if statement! 
       return 1 + CountWhoHasTwoSameSons(Head.GetLeft()) + 
       CountWhoHasTwoSameSons(Head.GetRight()); 

} 

錯誤「不是所有的路徑都返回一個值」是正確的。如果您的執行流程到達第三個if語句並且它是假的,那麼沒有返回值。你的功能被定義爲總是返回一個int,並且這種情況不在考慮之中。

因此,嘗試這樣的事情來解決這個問題:

public static int CountWhoHasTwoSameSons(BinNode<int> Head) 
{ 
    if (Head != null) 
    { 
     if (IsLeaf(Head)) 
      return 1; 

     if (Head.HasLeft() && Head.HasRight()) 
     { 
      if (Head.GetRight().GetValue() == Head.GetLeft().GetValue())) 
       return 1 + CountWhoHasTwoSameSons(Head.GetLeft()) + CountWhoHasTwoSameSons(Head.GetRight());  
     } 
    } 
    return 0; 
} 
+0

它不是爲我工作 –

+0

你能指出新的錯誤? – 0xDEFACED

+0

我編輯的問題,它返回它的0(見主) –

2

你需要添加If語句之外的回報,編譯器不能工作了,如果這個函數會返回一些與否。如果你可以在返回0的函數的末尾添加一個return語句,它應該可以工作。不是最喜歡的修復,你應該真的重寫函數,所以返回實際上不僅僅是一個令編譯器滿意的方式,它應該可以工作。

丹尼

+0

聖地亞哥瓦雷拉說什麼。在我開始之前,我沒有看到你的答案。 – dannyhut

+0

沒有問題的朋友:) – 0xDEFACED