Wednesday, May 11, 2011

binary search tree c/c++

Following example code is an implementation of binary search tree in C++ language.
Binary search tree is a data structure that shows log(n) search time.


// tree node.
typedef struct _tree
{
     int data;
     struct _tree *left, *right;
}tree


// Search function.
//
tree *search(tree *root, int key)
{
     while(root != NULL)
     {
          if( key == root->key ) return root;
          else if( key < root->key) root=root->left;
          else root=root->right;
     }
     return NULL;
}

// Insert function.
void insert_tree(tree **root, int key)
{
     tree p, t;                              //p for parent, t for temp node
     tree n;                                 //n for new node

     p=NULL;
     t=*root;

     while(t!=NULL)
     {
          if(key==t->key) return;    
          if(key < t->key)             
               t=t->left;
          else
               t=t->right;
     }

     n=(tree*)malloc(sizeof(tree));        
     n->key=key;                            
     n->left=n->right=NULL;           

     if(p!=NULL)                          
     {
          if(key < p->key)            
               p->left=n;
          else                            
               p->right=n;
     }else *root=n;                
}