how can I Write a code with these requirements? this is the question: check if there is a node with key K in the tree T, and if so, return a reference to this node. If the tree is empty, report that the node was not found and stop. Otherwise, compare K with the key value of the root node X.
- If K=X, issue a link to this node and stop.
- If K>X, recursively search for the key K in the right subtree of T.
- If K<X, recursively search for the key K in the left subtree of T.
This is what i found:
public GenBT<T> Find(GenBT<T> k, T inf){ 
if (k == null) return null; 
else 
switch (inf.CompareTo(k.inf)){ 
case 1: return Find(k.RT, inf); 
case -1: return Find(k.LT, inf); 
case 0: return k; 
default: return null;} 
};
but I also found that if I want to search or find in BST I have to use a code like this :
struct node* search(int data){
   struct node *current = root;
   printf("Visiting elements: ");
    
   while(current->data != data){
    
      if(current != NULL) {
         printf("%d ",current->data);
            
         //go to left tree
         if(current->data > data){
            current = current->leftChild;
         }  //else go to right tree
         else {                
            current = current->rightChild;
         }
            
         //not found
         if(current == NULL){
            return NULL;
         }
      }         
   }
   
   return current;
}
These two look very different and I don't know which way is right and in general what is the right way of solving this question
 
    