Search Tutorials

Saturday, 20 April 2013

C code to implement Binary Search Tree without using Recursion

/* C program to implement binary search tree and display all node without using recursion  */

#include <stdio.h>
#include <conio.h>
#include <malloc.h>

struct node
       {
         int data;
         struct node *lc,*rc;
       };

 typedef struct node NODE;

 int top=-1,stack[20];
 void create(NODE **,int);
 void inorder(NODE *);
 void main()
     {
       NODE *root=NULL;
       int data;
       char ch;
       clrscr();
       printf("Enter the root element:-        ");
       scanf("%d",&data);
       create(&root,data);
    while(1)
     {
      printf("\n   MENU \n");
      printf("\n1.Insert.");
      printf("\n2.Display.");
      printf("\n3.Exit\n");
      printf("\nEnter your choice:-    ");
      fflush(stdin);
     scanf("%c",&ch);
     switch(ch)
        {
         case '1':
              printf("\nEnter the data :-    ");
              scanf("%d",&data);
              create(&root,data);
              break;
         case '2':
              printf("\nIn-order Traversal:\n");
              inorder(root);
              break;
         case '3':
              exit(1);
         default:
             printf("\nYou have entered a wrong choice.");
        }
     }
  }

/* Creating Binary Search Tree */

void create(NODE **root,int d)
     {

       if(*root==NULL)
      {
        *root=(NODE *)malloc(sizeof(NODE));
        (*root)->data=d;
        (*root)->lc=NULL;
        (*root)->rc=NULL;
        return;
      }
    else
      {
        if( d < (*root)->data )
           create(&((*root)->lc),d);
        if( d > (*root)->data )
           create(&((*root)->rc),d);
        if( d == (*root)->data )
           printf("\nData already exist.");
       }
     }

/* Displaying all elements of binary search tree using stack */

void inorder(NODE *root)
   {
      NODE *ptr;
      (ptr)=(root);

      while(top!=-1||(ptr)!=NULL)
      {
    if((ptr)!=NULL)
    {
       stack[++top]=(ptr);
       (ptr)=(ptr)->lc;
      }
      else
      {
    (ptr)=stack[top--];
    printf("%d\t",(ptr)->data);
    (ptr)=(ptr)->rc;
      }
   }
}

/* Output of Binary Search Tree without using recursion Program */

C code to implement Binary Search Tree without using recursion
Output of BST without using recursion

C code to implement Binary Search Tree without using recursion
Output of BST without using recursion

For more related to Data Structure see List of Data Structure Programs. If you like this program, Please share and comment to improve this blog.

3 comments:

  1. Title is missleading! you used recursion while create binary search tree

    ReplyDelete
  2. sir you used recursion. please submit without recursion.

    ReplyDelete
  3. You used recursion and give a title without recursion !!

    ReplyDelete

Back to Top