繁体   English   中英

具有一个参数的递归搜索二叉搜索树

[英]Recursive Search Binary Search Tree with one parameter

我正在尝试使用 C# 中的递归方法搜索二叉搜索树。

到目前为止,我能够使用两个参数成功执行此方法:

public bool Search(int value, Node start)
{
     if(start == null) {   
          return false;
     }

     else if(value == start.value) {
          return true;
     }

     else {
          if(value < start.value) {
                 Search(value, start.LeftChild.value);
          }
         
          else {
                 Search(value, start.RightChild.value);
          }
     }
}

但是我想看看是否有一种方法可以只使用一个参数,例如使用以下方法签名:

public bool Search(int value){}

我还有以下可用于访问树的内容:

public class BinarySearchTree
{
     private Node<int> root;
     public Node<int> Root { get => root; set => root = value; }

     public BinarySearchTree()
     {
          this.root = null;
     }
}

如果有办法只使用一个参数,例如使用以下方法签名:

当然。 使其成为 Node 类中的方法。

public class Node
{
    public Node LeftChild, RightChild;
    public int value;

    public bool Search(int value)
    {
         if (value == this.value) 
         {
              return true;
         }
         else 
         {
              if (value < this.value) 
              {
                  return this.LeftChild?.Search(value) ?? false;
              }
              else 
              {
                  return this.RightChild?.Search(value) ?? false;
              }
         }
    }
}

然后对于树将其称为tree.Root.Search(0);

public bool Search(int value)
{
     return SearchTree(value, root);

     bool SearchTree(int value, Node<int> start)
     {
          if(start == null)
               return false;
    
          else if(value == start.Value)
               return true;
    
          else 
          {
               if(value < start.Value)
                   return SearchTree(value, start.LeftChild);

               else
                   return SearchTree(value, start.RightChild);
          }
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM