jain12

Convert a sorted array into BST

Mar 29th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 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 Inorder(Node* root){
  15.   if(root==NULL)
  16.     return;
  17.   Inorder(root->left);
  18.   cout<<" "<<root->data;
  19.   Inorder(root->right);
  20.   }
  21.  
  22. void Insert(Node **root_ref,int key){
  23.   if(*root_ref==NULL){
  24.     *root_ref=new Node(key);
  25.     return;
  26.     }
  27.   if((*root_ref)->data<key)
  28.     Insert(&((*root_ref)->right),key);
  29.   else
  30.      if((*root_ref)->data>key)
  31.        Insert(&((*root_ref)->left),key);
  32.   }
  33.  
  34. Node* ConvertIntoBST(int arr[],int n){
  35.   Node* root=NULL;
  36.   for(int i=0;i<n;i++)
  37.     Insert(&root,arr[i]);
  38.   return root;
  39.   }
  40.  
  41. int main(){
  42.  Node *root=NULL;
  43.  cout<<"enter total no. of elements in an array ";
  44.  int n;
  45.  cin>>n;
  46.  cout<<"enter elements in sorted order ";
  47.  int arr[n];
  48.  for(int i=0;i<n;i++)
  49.     cin>>arr[i];
  50.  root=ConvertIntoBST(arr,n);
  51.  Inorder(root);
  52.  }
Add Comment
Please, Sign In to add comment