Advertisement
LZsolar

SMMR-083: Binary Search Tree

Mar 27th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node{
  4.     int data;
  5.     node *left;
  6.     node *right;
  7.    
  8.     node(int n){
  9.         data=n;
  10.         left=NULL;
  11.         right=NULL;
  12.     }
  13. }*root=NULL;
  14. typedef struct node nodeT;
  15.  
  16. nodeT* insertNode(nodeT *root,int data){
  17.    nodeT *curr=root;
  18.     if(curr==NULL){
  19.         return root=new nodeT(node(data));
  20.     }
  21.     nodeT *prev;
  22.     while(curr!=NULL){
  23.         prev=curr;
  24.         if(curr->data<=data){curr=curr->right;}
  25.         else{curr=curr->left;}
  26.     }
  27.     if(prev->data<=data){prev->right=new nodeT(node(data));}
  28.     else{prev->left=new nodeT(node(data));}
  29.  
  30.     return root;
  31. }
  32.  
  33. void printT(nodeT *curr,int data){
  34.     deque<int> q;
  35.     bool found=false;
  36.     while(curr!=NULL){
  37.         q.push_back(curr->data);
  38.         if(curr->data==data){found=true;}
  39.         if(curr->data<=data){curr=curr->right;}
  40.         else{curr=curr->left;}
  41.     }
  42.     if(found){    
  43.         while(!q.empty()){
  44.             if(q.back()!=data){q.pop_back();}
  45.             else{break;}
  46.         }    
  47.     }
  48.  
  49.         while(!q.empty()){
  50.             printf("%d ",q.front());
  51.             q.pop_front();
  52.         }
  53.         if(!found){printf("0");}
  54.    
  55.    
  56. }
  57.  
  58. int main(){
  59.     int n;scanf("%d",&n);
  60.    
  61.     for(int i=0;i<n;i++){
  62.         int a; scanf("%d",&a);    
  63.        
  64.         root=insertNode(root,a);
  65.     }
  66.     scanf("%d",&n);
  67.     for(int i=0;i<n;i++){
  68.         int a; scanf("%d ",&a);
  69.         printT(root,a);
  70.         printf("\n");
  71.     }
  72.    
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement