2016-11-19 83 views
1

我想为我的树编写一个搜索算法,但我被困住了。我使用递归函数,但递归部分有错误。您可以在调试时找到它。在树中搜索算法

private Node SeachNode(Node node, IComparable value) 
     { 


      if (node == null) return null; 

      int comp = value.CompareTo(node.Letter.LetterName); 

      if (comp == 0) return node; //Found it 
      if (comp < 0) SeachNode(node.Left, value); //The item must be in the left subtree 
      return SeachNode(node.Right, value); // The item must be in the right subtree 
     } 

在这段代码中,我尝试在树中找到我的值。例如,我想在我的树中搜索“ACD”节点,即时从根开始搜索。如果root为null,则退出。否则,比较一下。如果root没有回答,则返回root。如果比较返回-1,检查根的左侧。但是代码并没有转到root的权利。我想这不是因为return语句。

谢谢你的帮助:)

+0

请阅读[MCVE]指南并提供适当的样本来证明问题。到目前为止,您发布的代码没有什么特别的错误。 –

回答

1

您需要使用return语句返回每次递归调用的价值,无论是向左和向右,以向后传播的搜索结果。

if (comp == 0) return node; //Found it 
if (comp < 0) return SeachNode(node.Left, value); //The item must be in the left subtree 
return SeachNode(node.Right, value); // The item must be in the right subtree 
+0

没有它没有。再检查一遍。例如ROOT A,在RIGHT C的左B中,您正在搜索C.使用ROOT的代码检查返回-1。走到左边,检查A和C -1。再次左转和左转为空。在这个时候函数返回null,除非它必须检查正确:( – Berkin

+2

@Berkin你没有提供演示问题的示例。这个答案修复了印刷错误(在其中一个分支中缺少'return'),但它没有必要修复您遇到的特定问题(正确的代码比您提供的代码有更好的工作机会,但如果数据无效,则可能无法工作)。 –