Kth Smallest Element in a BST @LeetCode

PROBLEM :

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ? k ? BST's total elements.

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        int min ;
        KthSallestEle(root,&k,&min) ;
        return min ;
    }
   
    void KthSallestEle(TreeNode *root,int *k,int *min){
        if(root->left)
            KthSallestEle(root->left,&(*k),&(*min)) ;
        (*k)-- ;
        if((*k)==0){
            (*min)=root->val ;
            return ;
        }
        if(root->right)
            KthSallestEle(root->right,&(*k),&(*min)) ;
    }
};

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

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 )