jain12

print elements between a given range

Mar 30th, 2020
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5.   public:
  6.       int data;
  7.       Node *left,*right;
  8.       Node(int key){
  9.         data=key;
  10.         left=right=NULL;
  11.         }
  12.   };
  13.  
  14. void Print(Node* root,int first,int last){
  15.   if(root==NULL)
  16.     return;
  17.   if(first<root->data)
  18.     Print(root->left,first,last);
  19.   if(root->data>=first && root->data<=last)
  20.     cout<<" "<<root->data;
  21.   if(root->data<last)
  22.     Print(root->right,first,last);
  23.   }
  24.  
  25. void Insert(Node **root_ref,int key){
  26.   if(*root_ref==NULL){
  27.     *root_ref=new Node(key);
  28.     return;
  29.     }
  30.   if((*root_ref)->data<key)
  31.     Insert(&((*root_ref)->right),key);
  32.   else
  33.      if((*root_ref)->data>key)
  34.        Insert(&((*root_ref)->left),key);
  35.   }
  36.  
  37. int main(){
  38.  Node *root=NULL;
  39.  Insert(&root,5);
  40.  Insert(&root,7);
  41.  Insert(&root,2);
  42.  Insert(&root,8);
  43.  int k1=0,k2=10;
  44.  Print(root,k1,k2);
  45.  return 0;
  46.  }
Add Comment
Please, Sign In to add comment