C Program for Binary Search Tree Creation and Traversals.
Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | #include <stdlib.h> typedef struct tnode { int data; struct tnode *right,*left; }TNODE; TNODE *CreateBST(TNODE *, int); void Inorder(TNODE *); void Preorder(TNODE *); void Postorder(TNODE *); main() { TNODE *root=NULL; /* Main Program */ int opn,elem,n,i; do { clrscr(); printf("\n ### Binary Search Tree Operations ### \n\n"); printf("\n Press 1-Creation of BST"); printf("\n 2-Traverse in Inorder"); printf("\n 3-Traverse in Preorder"); printf("\n 4-Traverse in Postorder"); printf("\n 5-Exit\n"); printf("\n Your option ? "); scanf("%d",&opn); switch(opn) { case 1: root=NULL; printf("\n\nBST for How Many Nodes ?"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("\nRead the Data for Node %d ?",i); scanf("%d",&elem); root=CreateBST(root,elem); } printf("\nBST with %d nodes is ready to Use!!\n",n); break; case 2: printf("\n BST Traversal in INORDER \n"); Inorder(root); break; case 3: printf("\n BST Traversal in PREORDER \n"); Preorder(root); break; case 4: printf("\n BST Traversal in POSTORDER \n"); Postorder(root); break; case 5: printf("\n\n Terminating \n\n"); break; default: printf("\n\nInvalid Option !!! Try Again !! \n\n"); break; } printf("\n\n\n\n Press a Key to Continue . . . "); getch(); }while(opn != 5); } TNODE *CreateBST(TNODE *root, int elem) { if(root == NULL) { root=(TNODE *)malloc(sizeof(TNODE)); root->left= root->right = NULL; root->data=elem; return root; } else { if( elem < root->data ) root->left=CreateBST(root->left,elem); else if( elem > root->data ) root->right=CreateBST(root->right,elem); else printf(" Duplicate Element !! Not Allowed !!!"); return(root); } } void Inorder(TNODE *root) { if( root != NULL) { Inorder(root->left); printf(" %d ",root->data); Inorder(root->right); } } void Preorder(TNODE *root) { if( root != NULL) { printf(" %d ",root->data); Preorder(root->left); Preorder(root->right); } } void Postorder(TNODE *root) { if( root != NULL) { Postorder(root->left); Postorder(root->right); printf(" %d ",root->data); } } |
Awesome man ! It helped me in my Computer programming lab 🙂
works much good……
good job.
Its good…
heeeheheheheheee thanq …….
dis s helps fa me too in computer lab :()
super
Please post sample input and output 🙂
how to delete one element.
GOOD ONE.. 🙂