Bird
Raised Fist0
DSA Cprogramming

Kth Smallest Element in BST in DSA C

Choose your learning style10 modes available
Mental Model
A binary search tree keeps smaller values on the left and bigger on the right, so the smallest values appear first if we look from left to right.
Analogy: Imagine a sorted bookshelf where smaller books are on the left and bigger books are on the right; to find the kth smallest book, you count from the left shelf to the right.
      5
     / \
    3   7
   / \   \
  2   4   8
 ↑ (root)
Dry Run Walkthrough
Input: BST: 5 -> 3 -> 7 -> 2 -> 4 -> 8, find 3rd smallest element
Goal: Find the 3rd smallest value in the BST
Step 1: Traverse left from 5 to 3
5 -> [3 ↑] -> 7 -> 2 -> 4 -> 8
Why: Left subtree has smaller values, so start there
Step 2: Traverse left from 3 to 2
5 -> 3 -> 7 -> [2 ↑] -> 4 -> 8
Why: Keep going left to find smallest values
Step 3: Visit 2 (1st smallest), move back to 3
5 -> [3 ↑] -> 7 -> 2 -> 4 -> 8
Why: 2 is the smallest, now check next bigger
Step 4: Visit 3 (2nd smallest), move to right child 4
5 -> 3 -> 7 -> 4 ↑ -> 8
Why: 3 is next smallest, check right subtree for next
Step 5: Visit 4 (3rd smallest), stop search
5 -> 3 -> 7 -> [4 ↑] -> 8
Why: Found 3rd smallest element
Result:
3rd smallest element is 4
Annotated Code
DSA C
#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)++;
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
OutputSuccess
3th smallest element is 4
Complexity Analysis
Time: O(h + k) because we traverse down the tree height h and visit k nodes in order
Space: O(h) due to recursion stack for tree height h
vs Alternative: Naive approach sorts all nodes O(n log n), this uses BST property to do less work
Edge Cases
k is larger than number of nodes
Returns -1 indicating kth smallest does not exist
DSA C
if (root == NULL || *count >= k) return;
Empty tree
Returns -1 as no elements exist
DSA C
if (root == NULL || *count >= k) return;
k is 1 (smallest element)
Returns smallest element by visiting leftmost node
DSA C
if (*count == k) { *result = root->val; return; }
When to Use This Pattern
When you need the kth smallest or largest element in a BST, use inorder traversal counting nodes because it visits nodes in sorted order.
Common Mistakes
Mistake: Not stopping traversal after finding kth element, causing unnecessary work
Fix: Add condition to stop recursion once kth element is found
Mistake: Counting nodes incorrectly or not passing count by reference
Fix: Use pointer to count variable to track count across recursive calls
Summary
Finds the kth smallest element by traversing the BST in sorted order.
Use when you want the kth smallest value without sorting all nodes.
The key insight is that inorder traversal of BST visits nodes in ascending order.

Practice

(1/5)
1. What does the term kth smallest element in a BST mean?
easy
A. The element that appears in the kth position when BST elements are sorted in ascending order
B. The element with the kth largest value in the BST
C. The element at the kth level of the BST
D. The element with the kth highest frequency in the BST

Solution

  1. Step 1: Understand BST property

    A Binary Search Tree (BST) stores elements so that left subtree has smaller values and right subtree has larger values.
  2. Step 2: Define kth smallest element

    The kth smallest element is the one that appears in the kth position when all elements are sorted in ascending order.
  3. Final Answer:

    The element that appears in the kth position when BST elements are sorted in ascending order -> Option A
  4. Quick Check:

    kth smallest = kth in sorted order [OK]
Hint: Think of inorder traversal to get sorted order [OK]
Common Mistakes:
  • Confusing kth smallest with kth largest
  • Thinking kth smallest means kth level node
  • Assuming frequency matters
2. Which of the following C function signatures is correct to find the kth smallest element in a BST node structure struct Node?
easy
A. void kthSmallest(int root, int k);
B. int kthSmallest(struct Node root, int k);
C. int kthSmallest(struct Node* root, int k);
D. int kthSmallest(struct Node* root);

Solution

  1. Step 1: Understand function parameters

    The function needs the root pointer to the BST and the integer k to find kth smallest.
  2. Step 2: Check parameter types

    Passing struct Node* for root and int for k is correct. Return type should be int for the element value.
  3. Final Answer:

    int kthSmallest(struct Node* root, int k); -> Option C
  4. Quick Check:

    Correct signature includes pointer and k parameter [OK]
Hint: Use pointer for tree root and int for k [OK]
Common Mistakes:
  • Passing root by value instead of pointer
  • Missing k parameter
  • Wrong return type or missing return
3. Given the BST below and k = 3, what is the output of the function kthSmallest(root, 3)?
      5
     / \
    3   7
   / \   \
  2   4   8
medium
A. 5
B. 4
C. 3
D. 7

Solution

  1. Step 1: Perform inorder traversal

    Inorder traversal of BST visits nodes in ascending order: 2, 3, 4, 5, 7, 8.
  2. Step 2: Identify 3rd element in traversal

    The 3rd element is 4.
  3. Final Answer:

    4 -> Option B
  4. Quick Check:

    Inorder 3rd element = 4 [OK]
Hint: Inorder traversal gives sorted order; pick kth element [OK]
Common Mistakes:
  • Counting nodes incorrectly in traversal
  • Confusing preorder or postorder with inorder
  • Choosing root or other node instead of kth
4. Consider this buggy C code snippet to find kth smallest element in BST:
int count = 0;
int kthSmallest(struct Node* root, int k) {
    if (!root) return -1;
    int left = kthSmallest(root->left, k);
    if (left != -1) return left;
    count++;
    if (count == k) return root->data;
    return kthSmallest(root->right, k);
}
What is the main issue with this code?
medium
A. Global variable 'count' causes incorrect results on multiple calls
B. Function does not handle empty tree
C. Returns -1 for valid kth element
D. Does not traverse right subtree

Solution

  1. Step 1: Analyze use of 'count'

    The variable 'count' is global and not reset between calls, causing wrong counts if function called multiple times.
  2. Step 2: Understand impact on results

    Because 'count' is not reset, subsequent calls may return wrong kth smallest element or fail.
  3. Final Answer:

    Global variable 'count' causes incorrect results on multiple calls -> Option A
  4. Quick Check:

    Global count not reset breaks repeated calls [OK]
Hint: Avoid global counters; pass as function argument [OK]
Common Mistakes:
  • Ignoring global variable side effects
  • Assuming function works for multiple calls
  • Not resetting count before each call
5. You have a BST with nodes containing duplicate values. How would you modify the standard kth smallest element algorithm to correctly find the kth smallest unique element?
hard
A. Use preorder traversal instead of inorder
B. Count all nodes including duplicates normally
C. Remove duplicates from BST before traversal
D. Use inorder traversal and skip duplicates by comparing with previous visited value

Solution

  1. Step 1: Understand duplicates in BST

    Duplicates appear as multiple nodes with same value; inorder traversal visits them in sorted order including duplicates.
  2. Step 2: Modify traversal to skip duplicates

    Track previous visited value during inorder traversal; only increment count when current value differs from previous.
  3. Step 3: Find kth unique element

    Increment count only for unique values; when count equals k, return current node's value.
  4. Final Answer:

    Use inorder traversal and skip duplicates by comparing with previous visited value -> Option D
  5. Quick Check:

    Skip duplicates by comparing previous value [OK]
Hint: Track previous value to count unique elements [OK]
Common Mistakes:
  • Counting duplicates as separate elements
  • Using preorder traversal which is not sorted
  • Trying to remove duplicates instead of skipping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard