/**********************************************************************/ 
/*Program: To show operations in binary tree*/
/*Purpose:  Program to show traversals in bibary tree*/
/*Date   :  05-01-2005*/
/*Time   :  10:30*/  
/**********************************************************************/
#include
#include
#include
typedef struct BTree_t
{
   char data;
   struct BTree_t *llink;
   struct BTree_t *rlink;
}BTree;
/**************Function Declaration Begin**********/
BTree *binarytree( BTree *, char);
void preorder( BTree * );
void inorder( BTree * );
void postorder( BTree * );
/**************Function Declaration End**********/
void main()
{
   char c,data;
   BTree *p;
   //clrscr();
   printf( “\n\t\t Program to show traversal operations in a binary tree”);
   printf( “\n Enter data ( single character ) in PRE ORDER:” );
   p = ( BTree * )malloc( sizeof ( BTree ) );
   p = NULL;
   do
   {
        printf( “\n Enter data ( single character ):” );
        scanf( “%c”,&data );
        p=binarytree( p,data );
        fflush( stdin );
        printf( “\n Add some other node(press ‘y’ for yes):” );
        scanf(“%c”,&c);
        fflush( stdin );
   }while( c==’y’ );
   printf( “\n preorder traversal of a binary tree is:” );
   preorder( p );
   printf( “\n inorder traversal of a binary tree is:” );
   inorder( p );
   printf( “\n postorder traversal of a binary tree is:” );
   postorder( p );
getch();
}
/********** creation of binary tree **********/
/********** Function Definition begins **********/
BTree *binarytree( BTree *p, char data )
{
   if( p == NULL )
   {
        p =( BTree * )malloc( sizeof ( BTree ) );
        p->llink = NULL;
        p->rlink = NULL;
        p->data = data;
   }
   else
   if(data <>data)
        p->llink = binarytree( p->llink, data );
   else
   if(data >p->data)
        p->rlink = binarytree( p->rlink, data );
   else
        printf( “\n Enter is duplicate” );
   return( p );
}
/********** Function Definition ends **********/
/********** pre order traversing **********/
/********** Function Definition begins **********/
void preorder( BTree * p )
{
    if ( p != NULL )
   {
            printf( “%4c”, p->data );
            preorder( p->llink );
            preorder( p->rlink );
   }
}
/********** Function Definition ends **********/
/********** in order traversing **********/
/********** Function Definition begins **********/
void inorder( BTree * p )
{
    if (p != NULL)
    {
            inorder( p->llink );
            printf( “%4c”, p->data );
            inorder( p->rlink );
   }
}
/********** Function Definition ends **********/
/********** post order traversing **********/
/********** Function Definition begins **********/
void postorder( BTree * p )
{
    if ( p != NULL )
    {
            postorder( p->llink );
            postorder( p->rlink );
            printf( “%4c”, p->data );
   }
}
/********** Function Definition ends **********/
 
No comments:
Post a Comment