jain12

find kth smallest element in BST

Mar 29th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 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. //first method
  15. void AddNode(Node* root,int arr[],int total){
  16.    if(root==NULL)
  17.      return;
  18.    static int key_index=0;
  19.    if(key_index<total){
  20.      AddNode(root->left,arr,total);
  21.      arr[key_index++]=root->data;
  22.      AddNode(root->right,arr,total);
  23.      }
  24.    }
  25.  
  26. int FindSmallestNumber(Node* root,int k ){
  27.   int arr[k];
  28.   AddNode(root,arr,k);
  29.   return arr[k-1];
  30.   }
  31.  
  32. // second method
  33. Node* AddNode2(Node* root,int &count,int total){
  34.    if(root==NULL)
  35.      return NULL;
  36.    Node* left=AddNode2(root->left,count,total);
  37.    if(left)
  38.       return left;
  39.    if(count++==total)
  40.       return root;
  41.    return AddNode2(root->right,count,total);
  42.    }
  43.  
  44. Node* FindSmallestNumber2(Node* root,int k ){
  45.   int count=1;
  46.   return AddNode2(root,count,k);
  47.   }
  48.  
  49. void Insert(Node **root_ref,int key){
  50.   if(*root_ref==NULL){
  51.     *root_ref=new Node(key);
  52.     return;
  53.     }
  54.   if((*root_ref)->data<key)
  55.     Insert(&((*root_ref)->right),key);
  56.   else
  57.      if((*root_ref)->data>key)
  58.        Insert(&((*root_ref)->left),key);
  59.   }
  60.  
  61. int main(){
  62.  Node *root=NULL;
  63.  Insert(&root,5);
  64.  Insert(&root,7);
  65.  Insert(&root,2);
  66.  Insert(&root,8);
  67.  int k=2;
  68.  Node* temp=FindSmallestNumber2(root,k);
  69.  if(temp)
  70.    cout<<" "<<temp->data;
  71.  else
  72.    cout<<" value is not correct";
  73.  return 0;
  74.  }
Add Comment
Please, Sign In to add comment