LeetCode-in-All

230. Kth Smallest Element in a BST

Medium

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:

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
#include <stdio.h>
#include <stdlib.h>

// Helper struct to hold state across recursive calls
struct Solution {
    int k;
    int count;
    int val;
};

// Function to create a new tree node
struct TreeNode* createNode(int val) {
    struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    newNode->val = val;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

// Helper function to perform in-order traversal and find the k-th smallest element
void calculate(struct Solution* sol, struct TreeNode* node) {
    if (node == NULL || sol->count >= sol->k) {
        return;
    }

    if (node->left != NULL) {
        calculate(sol, node->left);
    }

    sol->count++;
    if (sol->count == sol->k) {
        sol->val = node->val;
        return;
    }

    if (node->right != NULL) {
        calculate(sol, node->right);
    }
}

// Function to find the k-th smallest element in the BST
int kthSmallest(struct TreeNode* root, int k) {
    struct Solution sol = {k, 0, 0};
    calculate(&sol, root);
    return sol.val;
}

// Helper function to free the tree memory
void freeTree(struct TreeNode* root) {
    if (root == NULL) return;
    freeTree(root->left);
    freeTree(root->right);
    free(root);
}