C Program to implement a binary search tree with insert and display operations

        /* Program to implement a binary search tree with insert and display operations. */
        #include <stdio.h>
        #include <stdlib.h>

        struct treenode
        {
            int data;
            struct treenode  *left;
            struct treenode  *right;
        };
        typedef struct treenode* tnode;
tnode insert( int x, tnode t )
        {
/* 1*/      if( t == NULL )
            { /* Create and return a one-node tree */
/* 2*/          t = malloc( sizeof( struct treenode ) );
           
                
/* 5*/              t->data = x;
/* 6*/              t->left = t->right = NULL;
               
            }
            else if( x < t->data )
/* 8*/          t->left = insert( x, t->left );
            else if( x > t->data )
/*10*/          t->right = insert( x, t->right );
            /* Else x is in the tree already; we'll do nothing */
/*11*/      return t;  /* Do not forget this line!! */
        }
        /* traverse a binary search tree in a LDR (Left-Data-Right) fashion */
     void inorder (tnode sr )
        {
         if ( sr != NULL )
         {
          inorder ( sr -> left ) ;    
                /* print the data of the node whose leftchild is NULL or the path has already been traversed */
          printf ( "\t%d", sr -> data ) ;
          inorder ( sr -> right ) ;
         }
         else
          return ;
        }
main( )
{
    tnode t=NULL;
    int i,j = 7;
    for( i = 0; i < 10; i++, j = ( j + 7 ) % 10 )
        t = insert( j, t );
    inorder (t);
    return 0;
}

Bhanu Namikaze

Bhanu Namikaze is an Ethical Hacker, Security Analyst, Blogger, Web Developer and a Mechanical Engineer. He Enjoys writing articles, Blogging, Debugging Errors and Capture the Flags. Enjoy Learning; There is Nothing Like Absolute Defeat - Try and try until you Succeed.

No comments:

Post a Comment