The Indian Engineer

Problem 230 Kth Smallest Element in a BST

Posted on Last edited 2 mins

Binary-Search-Tree Inorder-Traversal Dfs

Problem Statement

Link - Problem 230

Question

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes 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

Solution

/**
 * 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:
    void solve(TreeNode* root, int &cnt, int &ans, int k){
        if(root == nullptr)
            return;
        //left, root, right
        solve(root->left, cnt, ans, k);
        cnt++;
        if(cnt == k){
            ans = root->val;
            return;
        }
        solve(root->right, cnt, ans, k);
    }
    int kthSmallest(TreeNode* root, int k) {
        std::ios::sync_with_stdio(false);
        int cnt = 0;
        int ans;
        solve(root, cnt, ans, k);
        return ans;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Inorder Traversal O(n) O(1)

Explanation

1. Intuition

2. Implementation