Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- class Node{
- public:
- int data;
- Node *left,*right;
- Node(int key){
- data=key;
- left=right=NULL;
- }
- };
- //first method
- void AddNode(Node* root,int arr[],int total){
- if(root==NULL)
- return;
- static int key_index=0;
- if(key_index<total){
- AddNode(root->left,arr,total);
- arr[key_index++]=root->data;
- AddNode(root->right,arr,total);
- }
- }
- int FindSmallestNumber(Node* root,int k ){
- int arr[k];
- AddNode(root,arr,k);
- return arr[k-1];
- }
- // second method
- Node* AddNode2(Node* root,int &count,int total){
- if(root==NULL)
- return NULL;
- Node* left=AddNode2(root->left,count,total);
- if(left)
- return left;
- if(count++==total)
- return root;
- return AddNode2(root->right,count,total);
- }
- Node* FindSmallestNumber2(Node* root,int k ){
- int count=1;
- return AddNode2(root,count,k);
- }
- void Insert(Node **root_ref,int key){
- if(*root_ref==NULL){
- *root_ref=new Node(key);
- return;
- }
- if((*root_ref)->data<key)
- Insert(&((*root_ref)->right),key);
- else
- if((*root_ref)->data>key)
- Insert(&((*root_ref)->left),key);
- }
- int main(){
- Node *root=NULL;
- Insert(&root,5);
- Insert(&root,7);
- Insert(&root,2);
- Insert(&root,8);
- int k=2;
- Node* temp=FindSmallestNumber2(root,k);
- if(temp)
- cout<<" "<<temp->data;
- else
- cout<<" value is not correct";
- return 0;
- }
Add Comment
Please, Sign In to add comment