Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node
  5. {
  6.      int data;
  7.      node *left = NULL;
  8.      node *right = NULL;
  9.      node(){
  10.  
  11.      }
  12.      
  13.      node(int _data ,node *_left ,node *_right){
  14.        
  15.         data = _data;
  16.         left = _left;
  17.         right = _right;
  18.      }
  19.    
  20. };
  21.  
  22. struct tree
  23. {
  24.  
  25.    node *root=NULL;
  26.    
  27.    
  28.    void insert(int x){
  29.    
  30.        if(root==NULL){
  31.        
  32.           root = new node(x ,NULL ,NULL);
  33.        
  34.           return;
  35.        }
  36.        node *cur = root;
  37.        
  38.        while(1){
  39.        
  40.           if(x <= cur->data){
  41.  
  42.                    if(cur->left==NULL){
  43.            
  44.                 cur->left = new node(x ,NULL ,NULL);
  45.                 return;
  46.              }
  47.              else cur = cur->left ;
  48.            }
  49.           else if(x > cur->data){
  50.  
  51.              if(cur->right==NULL){
  52.            
  53.             cur->right = new node(x ,NULL ,NULL);
  54.             return;
  55.           }
  56.           else cur = cur->right ;
  57.         }
  58.  
  59.        }
  60.        
  61.        
  62.    }  
  63.  
  64.    void inorder(struct node *cur){
  65.        
  66.        if(cur!=NULL){
  67.        
  68.             inorder(cur->left);
  69.            
  70.             printf("%d" ,cur->data);
  71.            
  72.             inorder(cur->right);
  73.        
  74.           }
  75.    
  76.    }
  77.    
  78. };
  79.  
  80. int main(){
  81.    
  82.     struct tree a;
  83.    
  84.     a.insert(41);
  85.     a.insert(32);
  86.     a.insert(94);
  87.    
  88.     a.inorder();
  89.    
  90.    
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement