2017-03-25 29 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