Advertisement
nuray__alam

BST

Dec 10th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.81 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct node
  5. {
  6.     int key;
  7.     struct node *left;
  8.     struct node *right;
  9. }node;
  10.  
  11. node *creatnewnode(int key)
  12. {
  13.     node *n=(node*)malloc(sizeof(node));
  14.     n->left=NULL;n->right=NULL;
  15.     n->key=key;
  16.     return n;
  17. }
  18.  
  19.  
  20. node *insert(node *root,int key)
  21. {
  22.     if(root==NULL){
  23.         root=creatnewnode(key);
  24.         return root;
  25.     }
  26.     else if(key<=root->key){
  27.         root->left=insert(root->left,key);
  28.     }
  29.     else{
  30.         root->right=insert(root->right,key);
  31.     }
  32.     return root;
  33. }
  34.  
  35. void preorder(node *root)
  36. {
  37.     if(root==NULL) return;
  38.     printf("%d ",root->key);
  39.     if(root->left!=NULL) preorder(root->left);
  40.     if(root->right!=NULL) preorder(root->right);
  41.     return;
  42. }
  43.  
  44. void inorder(node *root)
  45. {
  46.     if(root==NULL) return;
  47.     if(root->left!=NULL) inorder(root->left);
  48.     printf("%d ",root->key);
  49.     if(root->right!=NULL) inorder(root->right);
  50.     return;
  51. }
  52.  
  53. void postorder(node *root)
  54. {
  55.     if (root==NULL)return;
  56.     if(root->left!=NULL) postorder(root->left);
  57.     if(root->right!=NULL) postorder(root->right);
  58.     printf("%d ",root->key);
  59.     return;
  60. }
  61.  
  62.  
  63. node *bstsearch(node *temp,int key)
  64. {
  65.     while(temp!=NULL){
  66.         if(temp->key==key) return temp;
  67.         if(key<=temp->key) temp=temp->left;
  68.         else temp=temp->right;
  69.     }
  70.     return temp;
  71. }
  72.  
  73.  
  74. int main()
  75. {
  76.     node *root=NULL;
  77.     node *temp=NULL;
  78.     root=insert(root,5);
  79.     root=insert(root,3);
  80.     root=insert(root,7);
  81.     root=insert(root,9);
  82.     root=insert(root,4);
  83.     preorder(root);
  84.     printf("\n");
  85.     postorder(root);
  86.     printf("\n");
  87.     inorder(root);
  88.     printf("\n");
  89.     temp=bstsearch(root,5);
  90.     if(temp==NULL) printf("there is no value\n");
  91.     else printf("There it is %d\n",temp->key);
  92.  
  93.     return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement