Home > Enterprise >  Recursive Search Binary Search Tree with one parameter
Recursive Search Binary Search Tree with one parameter

Time:06-05

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

CodePudding user response:

if there's a way to use only one parameter such as using the following method signature:

sure. make it a method in Node class.

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

then for tree call it as tree.Root.Search(0);

CodePudding user response:

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