Problem Statement

Given the root of a binary search tree, and an integer k, return the kth (1-indexedsmallest element in the tree.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints:

Problem Link

Kth Smallest Element in a BST - LeetCode

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // The basic idea is to perform an inorder traversal of the BST and keep a count variable (initilaized to 0)
    // which when gets incremented when it encounted a root node in the traversal. If its value becomes
    // equal to k return that node's value.
    int count = 0;
    void solve(TreeNode *root,int k,int &res)
    {
        if(!root)
        return;
        
        solve(root->left,k,res);
        count++;
        if(count==k)
        {
            res = root->val;
            return;
        }
        solve(root->right,k,res);
        
    }
    int kthSmallest(TreeNode* root, int k) {
        int res = -1;
       
       solve(root,k,res);
       
       return res;
    }
};

Similar Problem

Kth largest element in BST | Practice | GeeksforGeeks