Page 225 - DCAP407_DATA_STRUCTURE
P. 225
Data Structure
{
long digit;
clrscr();
puts("Enter integers: and 0 to quit");
scanf("%d",&digit); //Reads the first number to be inserted
while (digit!=0)
{
bintree=insert(bintree,digit); // Inserts the number entered
scanf("%d",&digit);
}
puts("Inorder traversing of bintree:\n");
inorder(bintree); //Calling inorder function to traverse
the tree
}
struct tree* insert(struct tree* bintree,long digit) //insert function is defined
{
if(bintree==NULL) //checks if the tree is empty
{
bintree=(struct tree*) malloc(sizeof(struct tree)); //Allocates memory for the tree
bintree->left=bintree->right=NULL; //Left and right sub-trees is set to NULL
/* The digit entered is assigned to the info element of the tree node*/
bintree->info=digit;
}
else
{
if(digit<bintree->info) //If the entered number is less than the data of the node
bintree->left=insert(bintree->left,digit); //insert the digit in the left sub-tree
else
/*If the entered number is greater than the data of the node*/
if(digit>bintree->info)
bintree->right=insert(bintree->right,digit); //insert the digit in the right sub-tree
else
if(digit==bintree->info) //If entered number is equal to data of
the node
{
//exits program after printing that duplicate node is present
puts("Duplicates node:program exited");
exit(0);
218 LOVELY PROFESSIONAL UNIVERSITY