#include <stdio.h>
#include <stdlib.h>
// Define BST node
typedef struct Node {
int val;
struct Node* left;
struct Node* right;
} Node;
// Create new node
Node* newNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// Insert value into BST
Node* insert(Node* root, int val) {
if (root == NULL) return newNode(val);
if (val < root->val) root->left = insert(root->left, val);
else root->right = insert(root->right, val);
return root;
}
// Helper function to find kth smallest
void kthSmallestHelper(Node* root, int k, int* count, int* result) {
if (root == NULL || *count >= k) return;
kthSmallestHelper(root->left, k, count, result); // go left
(*count)++;
if (*count == k) {
*result = root->val; // found kth smallest
return;
}
kthSmallestHelper(root->right, k, count, result); // go right
}
// Main function to find kth smallest
int kthSmallest(Node* root, int k) {
int count = 0;
int result = -1;
kthSmallestHelper(root, k, &count, &result);
return result;
}
int main() {
Node* root = NULL;
int values[] = {5, 3, 7, 2, 4, 8};
int n = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insert(root, values[i]);
}
int k = 3;
int ans = kthSmallest(root, k);
printf("%dth smallest element is %d\n", k, ans);
return 0;
}kthSmallestHelper(root->left, k, count, result); // go left
Traverse left subtree to find smaller values first
Count nodes visited in ascending order
if (*count == k) { *result = root->val; return; }
Stop when kth smallest is found
kthSmallestHelper(root->right, k, count, result); // go right
Traverse right subtree after left and current node
3th smallest element is 4