ann8497

bst

Aug 30th, 2019
679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5.  class node{
  6.      public:
  7.        int data;
  8.        node*left;
  9.        node*right;
  10.        node(int data){
  11.            data = data;
  12.            left = right = NULL;
  13.        }
  14.  };
  15.  
  16. node* insert(int data, node*root){
  17.     if(root == NULL){
  18.         node*temp = new node(data);
  19.         return temp;
  20.     }
  21.     if(data > root->data) root->right = insert(data, root->right);
  22.     else if(data < root->data) root->left =  insert(data, root->left);
  23.    
  24.     return root;
  25.      
  26. }
  27.  
  28. int search(int data, int level, node*head){
  29.    
  30.     if(head->data == data)return level;
  31.    
  32.     if(data > head->data)
  33.         return search(data ,  level + 1, head->right);
  34.     else return search(data , level + 1, head->left);
  35. }
  36.  
  37. vector<int> solve (vector<int> v,int n) {
  38.    
  39.    node*head = NULL;
  40.    
  41.    for(int i = 0; i<n; i++)
  42.        head = insert(v[i] , head);
  43.    
  44.    
  45.    cout<<head->data;
  46.    
  47.    vector<int>ans;
  48.  
  49.    for(int i = 0; i<n; i++){
  50.       ans.push_back(search(v[i],1,head));
  51.    }
  52.  
  53.   return ans;
  54. }
  55.  
  56. int main() {
  57.  
  58.     ios::sync_with_stdio(0);
  59.     cin.tie(0);
  60.     int N;
  61.     cin >> N;
  62.     vector<int> A(N);
  63.     for(int i_A=0; i_A<N; i_A++)
  64.     {
  65.         cin >> A[i_A];
  66.     }
  67.  
  68.     vector<int> out_;
  69.     out_ = solve(A,N);
  70.     cout << out_[0];
  71.     for(int i_out_=1; i_out_<N; i_out_++)
  72.     {
  73.         cout << " " << out_[i_out_];
  74.     }
  75. }
Add Comment
Please, Sign In to add comment