Answers for "kth smallest element in binary search tree"

C++
0

kth smallest element in binary search tree

#include<iostream>
using namespace std;
struct node
{
    int data;
    node* left;
    node* right;
};
int ans=0;
node* getnode(int value)
{
    node* temp=new node;
    temp->data=value;
    temp->left=NULL;
    temp->right=NULL;
    return temp;
}
node *insert_bst(node *roots,int value)
{
    if(roots==NULL)
    {
        return getnode(value);
    }
    if(roots->data>value)
    {
        roots->left=insert_bst(roots->left,value);
    }
    else if(roots->data<value)
    {
        roots->right=insert_bst(roots->right,value);
    }
    return roots;
}
void findsol(node* roots,int *kth)
{
    if(roots==NULL)
    {
        return;
    }
    else
    {
        findsol(roots->left,kth);
        (*kth)--;
        if((*kth)==0)
        {
            ans=roots->data;
        }
        findsol(roots->right,kth);
    }
}
int main()
{
    node* root=new node;
    root=NULL;
    int value;
    do{
        cin>>value;
        if(value>0)
        {
            root=insert_bst(root,value);
        }
    }while(value>0);
    int k;
    cin>>k;
    int* kth=&k;
    findsol(root,kth);
    cout<<ans;
    return 0;
}
Posted by: Guest on August-01-2021

Code answers related to "kth smallest element in binary search tree"

Browse Popular Code Answers by Language