Tree Search

/*
BST: Binary SeaRCh Tree, LC: Left Child, RC: Right Child, TN: Temp Node
*/
#include <stdio.h>
#include <stdlib.h>
struct node {
   int data;
   struct node *LC;
   struct node *RC;
};
struct node *root = NULL;
void insert(int data) {
   struct node *TN = (struct node*) malloc(sizeof(struct node));
   struct node *current;
   struct node *parent;
   TN->data = data;
   TN->LC = NULL;
   TN->RC = NULL;
   if(root == NULL) { //if tree is empty
      root = TN;
   } else {
      current = root;
      parent = NULL;
      while(1) {
         parent = current;
         if(data < parent->data) {//go to left of the tree
            current = current->LC;
            if(current == NULL) {//insert to the left
               parent->LC = TN;
               return;
            }
         }  //go to right of the tree
         else {
            current = current->RC;
            if(current == NULL) {//insert to the right
               parent->RC = TN;
               return;
            }
         }
      }
   }
}
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->LC;
      }
      //else go to right tree
      else {
         current = current->RC;
      }
      //not found
      if(current == NULL) {
         return NULL;
      }
   }
   return current;
}
int main() {
   int x;
   printf(“Enter tree nodes, -1 for exit.);
   do{
scanf(“%d”,&x);
insert(x);
   }while(x != -1);
   printf(“Enter item to search: “);
   scanf(“%d”,&x);
   struct node * temp = search(x);
   if(temp != NULL) {
      printf(“[%d] Element found.”, temp->data);
      printf(“\n”);
   }else {
      printf(“[ x ] Element not found (%d).\n”, x);
   }
   return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>