jain12

insertion and searching in a BST

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