Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 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 node *tree
  23. {
  24.  
  25.    node *root;
  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(cur->data<x){
  41.            
  42.                   cur  = cur->right;
  43.              }
  44.           else if(cur->data>=x){
  45.            
  46.             cur = cur->left;
  47.           }
  48.           if(cur==NULL){
  49.            
  50.             cur = new node(x ,NULL ,NULL);
  51.             return;
  52.           }
  53.        }
  54.        
  55.        
  56.    }   
  57.    
  58.    void print(){
  59.    
  60.     printf("%d %d %d" ,root->data ,root->left->data ,root->right->data);
  61.    }
  62.    
  63. };
  64.  
  65. int main(){
  66.    
  67.     struct tree a;
  68.    
  69.     a.insert(41);
  70.     a.insert(32);
  71.     a.insert(94);
  72.    
  73.     a.print();
  74.    
  75.    
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement