Wednesday 28 June 2017

binary search tree

typedef struct node
{
 int value;
 struct node *left;
 struct node *right;
}mynode;

mynode *root=NULL;

int main()
{
 mynode *temp;
 root = NULL;

 // Construct the tree
 add(19);
 add(20);
 ...
 add(11);
 
 inorder(root);
 
 return(0);
} 


// Function to add a new value to a Binary Search Tree
add(int value)
{
 mynode *temp, *prev, *cur;

 temp = malloc(sizeof(mynode));
 temp->value = value;
 temp->left = NULL;
 temp->right = NULL;
 if(root == NULL)
 {
   root = temp;
 }
 else
 {
   prev = NULL;
   cur = root;
   while(cur)
    {
      prev = cur;
      cur = (value < cur->value)? cur->left : cur->right;
    }

   if(value > prev->value)
      prev->right = temp;
   else
      prev->left = temp;
 }
}
 
 

/*Traverse the tree in Preorder*/

preorder(mynode *root)
{
 if(root)
 {
  printf("Value : [%d]", root->value);
  preorder(root->left);
  preorder(root->right);
 }
} 

/* Traverse the tree in Postorder*/
postorder(mynode *root)
{
 if(root)
 {
   postorder(root->left);
   postorder(root->right);
   printf("Value : [%d]", root->value);
 }
} 
 
/*Travers the tree in Inorder*/
inorder(mynode *root)
{
 if(root)
 {
   inorder(root->left);
   printf("Value : [%d]", root->value);
   inorder(root->right);
 }
} 

No comments:

Post a Comment