Advertisement
rodan0818

Binary Search Tree

Jul 17th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node {
  4. int value;
  5. struct node *left,*right;
  6. };
  7. struct node * createNode(int val){
  8.     struct node *newNode = malloc(sizeof(struct node));
  9.     newNode->value=val;
  10.     newNode->left=newNode->right=NULL;
  11.     return newNode;
  12. }
  13. struct node *insertNode(struct node *root,int val){
  14. if(root==NULL){
  15.     return createNode(val);
  16. }
  17. if(val<root->value){
  18.     return insertNode(root->left,val);
  19. }
  20. else{
  21.     return insertNode(root->right,val);
  22. }
  23. }
  24. void traverse(struct node *root){
  25. if(root==NULL) return;
  26.     traverse(root->left);
  27.     printf("%d->",root->value);
  28.     traverse(root->right);
  29. }
  30. int main (void){
  31. struct node *root=NULL;
  32. int ch=0 , val,cx=0;
  33.  
  34. while(1){
  35. printf("Choose From The Given Options \n1.Insert\t2.Delete\t3.Traverse\t4.Exit\n");
  36. scanf("%d",&ch);
  37. switch(ch){
  38. case 1:
  39.     printf("Enter The Value/Key To Insert \n");
  40.     scanf(" %d",&val);
  41.      if (cx==0){
  42.         root =insertNode(root,val);
  43.         cx++;
  44.     }
  45.     else{
  46.         insertNode(root,val);
  47.     }
  48.  
  49.     break;
  50. case 2:break;
  51. case 3:traverse(root);
  52. printf("\n");
  53.     break;
  54. case 4:exit(0);
  55.  
  56. }}
  57. return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement