Find k-th smallest element in BST

PROBLEM :

Given root of binary search tree and K as input, find K-th smallest element in BST. Your task is to return the K-th smallest element in BST from the function k_smallest_element().

Note: The Time Complexity will be O(h) where h is the height of the Tree.

Input:
The first line of input will contain the number of test cases T. Then T test cases follow. First line of every test case will be n, denoting the number of nodes in the BST. Second line of every test case will be n spaced integers denoting the Integer value of Nodes in BST. Third line of every test case will be k, denoting kth the smallest number.

Output:
For each test case, output will be the kth smallest element of BST.

Constraints:
1<=T<=100
1<=N<=100
1<=K<=N

Example(To be used only for expected output):
Input:
1
5
20 8 4 22 12
3

Output:
12

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*Complete the function below
Node is as follows:
struct Node
{
    int data;
    int lCount;

    Node* left;
    Node* right;
};*/

int KthSmallestElement(Node *root, int k)
{
    int ans ;
    if(root)
    {
        while(root)
        {
            if(root->lCount+1==k)
            {
                ans=root->data ;
                break ;
            }
            else if(root->lCount<k)
            {
                k=k-(root->lCount+1) ;
                root=root->right ;
            }
            else
                root=root->left ;
        }
    }
    return ans ;
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )