Advertisement
TAHMID37

Task 3 omar

Aug 12th, 2021
1,029
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define pi acos(-1.0)
  4. #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
  5. #define ll long long
  6. #define pb push_back
  7. #define fi first
  8. #define se second
  9. #define in insert
  10.  
  11. struct bst {
  12.  
  13.     ll data;
  14.     ll left_subtree_size;
  15.     ll right_subtree_size;
  16.     struct bst* left;
  17.     struct bst* right;
  18.     struct bst* parent;
  19.  
  20.  
  21. };
  22.  
  23. struct bst* root=NULL;
  24.  
  25. void insert_bst(ll x)
  26. {
  27.     struct bst*temp=new bst();
  28.  
  29.     temp->data=x;
  30.     temp->left=NULL;
  31.     temp->right=NULL;
  32.     temp->parent=NULL;
  33.     temp->left_subtree_size=temp->right_subtree_size=0;
  34.  
  35.  
  36.     if(root==NULL)
  37.     {
  38.         root=temp;
  39.         return;
  40.     }
  41.  
  42.     struct bst * cur=root;
  43.  
  44.     while(1)
  45.     {
  46.         if(x>=cur->data)
  47.         {
  48.             cur->right_subtree_size++;
  49.  
  50.             if((cur->right)==NULL)
  51.             {
  52.                 cur->right=temp;
  53.                 temp->parent=cur;
  54.                 return ;
  55.  
  56.             }
  57.             else
  58.                 cur=cur->right;
  59.         }
  60.         else if(x<cur->data)
  61.         {
  62.             cur->left_subtree_size++;
  63.  
  64.             if((cur->left)==NULL)
  65.             {
  66.                 cur->left=temp;
  67.                 temp->parent=cur;
  68.                 return ;
  69.  
  70.             }
  71.             else
  72.                 cur=cur->left;
  73.         }
  74.     }
  75.  
  76.  
  77. }
  78.  
  79.  
  80. bool search(bst *root,int data)
  81. {
  82.     if(root==NULL)
  83.         return false;
  84.     else if(root->data==data)
  85.         return true;
  86.     else if(root->data >data)
  87.         return search(root->left,data);
  88.     else
  89.         return search(root->right,data);
  90. }
  91.  
  92.  
  93.  
  94.  
  95. int main()
  96. {
  97.     insert_bst(8);
  98.  
  99.     insert_bst(10);
  100.  
  101.     insert_bst(14);
  102.  
  103.     insert_bst(13);
  104.  
  105.     insert_bst(3);
  106.  
  107.     insert_bst(6);
  108.  
  109.     insert_bst(1);
  110.  
  111.     insert_bst(4);
  112.  
  113.     insert_bst(7);
  114.  
  115.  
  116.  
  117.     cout<<"Search 6 : ";
  118.     if(search(root,6))
  119.         cout<<"Found"<<endl;
  120.     else
  121.         cout<<"Not Found"<<endl;
  122.  
  123.  
  124. }
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement