SuitNdtie

Binary Search Tree TASK_083

Mar 9th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include<iostream>
  2. #include<vector>
  3. using namespace std;
  4.  
  5. typedef struct node{
  6.     int data;
  7.     struct node *left;
  8.     struct node *right;
  9. }nodeT;
  10.  
  11. nodeT* newnode(int data){
  12.     nodeT* newNode = new(nodeT);
  13.     newNode->data = data;
  14.     newNode->left = NULL;
  15.     newNode->right = NULL;
  16.     return newNode;
  17. }
  18.  
  19. nodeT* addBST(nodeT* root,int data){
  20.     nodeT* Nnode = newnode(data);
  21.     if(root == NULL){
  22.         return Nnode;
  23.     }
  24.     if(data >= root->data){
  25.         root->right = addBST(root->right,data);
  26.     }else{
  27.         root->left = addBST(root->left,data);
  28.     }
  29.     return root;
  30. }
  31.  
  32. typedef struct{
  33.     int id;
  34.     int count;
  35. }ct;
  36.  
  37. int index(vector<ct> table,int key){
  38.     for(int i=0;i<table.size();i++){
  39.         if(table[i].id == key){
  40.             return i;
  41.         }
  42.     }
  43.     return -1;
  44. }
  45.  
  46. void searchBST(nodeT *root,int key,vector<ct> table){
  47.     if(root == NULL){
  48.         cout << "0";
  49.         return;
  50.     }
  51.     cout << root->data << " ";
  52.     if(root->data < key){
  53.         searchBST(root->right,key,table);
  54.     }else if(root->data > key){
  55.         searchBST(root->left,key,table);
  56.     }else if(root->data == key){
  57.         if(--table[index(table,key)].count > 0){ // has left
  58.             searchBST(root->right,key,table);
  59.         }else{
  60.             return;
  61.         }
  62.     }
  63. }
  64.  
  65. int main()
  66. {
  67.     nodeT *root;
  68.     root = NULL;
  69.     int n;
  70.     cin>>n;
  71.     vector<ct> table;
  72.    
  73.     for(int i=0;i<n;i++){
  74.         int x;
  75.         cin>>x;
  76.         root = addBST(root,x);
  77.         int j;
  78.         for(j=0;j<table.size();j++){
  79.             if(table[j].id == x){
  80.                 table[j].count++;
  81.                 break;
  82.             }
  83.         }
  84.         if(j == table.size()){
  85.             table.push_back({x,1});
  86.         }
  87.     }
  88.     int m;
  89.     cin>>m;
  90.     for(int i=0;i<m;i++){
  91.         int x;
  92.         cin>>x;
  93.        
  94.         int temp = table[index(table,x)].count;
  95.         searchBST(root,x,table);
  96.         table[index(table,x)].count = temp;
  97.         cout<<endl;
  98.     }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment