Search code examples
c#recursionbinary-search-tree

Recursive Search Binary Search Tree with one parameter


I am trying to search through a binary search tree using a recursive method in C#.

So far I am able to successfully execute this method using two parameters:

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);
          }
     }
}

However I would like to see if there's a way to use only one parameter such as using the following method signature:

public bool Search(int value){}

I also have the following that I can use to access the tree:

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

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

Solution

  • 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);
              }
         }
    }