📖 Scenario: You are working with a Binary Search Tree (BST) that stores numbers in a way that smaller numbers go to the left and larger numbers go to the right. You want to find the kth smallest number in this tree, which means the number that would appear in position k if you listed all numbers in order.
🎯 Goal: Build a program that creates a BST, sets a value for k, finds the kth smallest element in the BST using an in-order traversal, and prints the result.
📋 What You'll Learn
Create a BST with the exact nodes given
Set an integer variable k to specify which smallest element to find
Implement an in-order traversal to find the kth smallest element
Print the kth smallest element found
💡 Why This Matters
🌍 Real World
Finding the kth smallest element in a BST is useful in databases and search engines where you want to quickly find ranked data like the 3rd cheapest product or 5th highest score.
💼 Career
Understanding BST traversal and selection algorithms is important for software engineers working on data retrieval, optimization, and systems that require efficient searching and sorting.
Progress0 / 4 steps
1
Create the BST nodes
Create a struct called Node with an integer val, and two pointers left and right. Then create the BST with these exact nodes and connections: root with value 5, root's left child with value 3, root's right child with value 7, left child's left child with value 2, left child's right child with value 4, right child's left child with value 6, right child's right child with value 8.
DSA C++
Hint
Start by defining the Node struct with a constructor. Then create the root node and add children exactly as described.
2
Set the value of k
Create an integer variable called k and set it to 3. This means you want to find the 3rd smallest element in the BST.
DSA C++
Hint
Just create an integer variable named k and assign it the value 3.
3
Implement in-order traversal to find kth smallest
Write a function called kthSmallest that takes Node* root and int k as parameters and returns the kth smallest integer in the BST. Use an in-order traversal (left, root, right) and a counter to find the kth smallest element.
DSA C++
Hint
Use a helper function inorder to visit nodes in order. Keep a counter and when it reaches k, save the node's value.
4
Print the kth smallest element
Use cout to print the result of calling kthSmallest(root, k). This will show the kth smallest element in the BST.
DSA C++
Hint
Call kthSmallest(root, k) and print the returned value using cout.
Practice
(1/5)
1. What does the Kth Smallest Element in BST problem ask you to find?
easy
A. The height of the Binary Search Tree
B. The element that is the Kth smallest value in the Binary Search Tree
C. The largest element in the Binary Search Tree
D. The sum of all elements in the Binary Search Tree
Solution
Step 1: Understand the problem statement
The problem asks to find the element that is the Kth smallest in the BST, meaning the element that would appear in position K if the BST elements were sorted.
Step 2: Clarify what Kth smallest means in BST context
Since BST stores elements in sorted order when traversed in-order, the Kth smallest element is the Kth element visited in an in-order traversal.
Final Answer:
The element that is the Kth smallest value in the Binary Search Tree -> Option B
Quick Check:
Kth smallest element = Kth element in in-order traversal [OK]
Hint: Think in-order traversal gives sorted order [OK]
Common Mistakes:
Confusing Kth smallest with Kth largest
Thinking it's about tree height
Summing elements instead of finding one
2. Which of the following C++ function signatures is correct for a function that finds the Kth smallest element in a BST node structure defined as struct TreeNode { int val; TreeNode* left; TreeNode* right; };?
easy
A. int kthSmallest(TreeNode* root, int k);
B. void kthSmallest(TreeNode root, int k);
C. int kthSmallest(TreeNode root, int* k);
D. int kthSmallest(TreeNode* root);
Solution
Step 1: Check parameter types for BST traversal
The function should receive a pointer to the root node to traverse the BST properly, so TreeNode* root is correct.
Step 2: Check parameters for K value
K is an integer input, so passing it as int k is correct. The function returns the Kth smallest value as an integer.
Final Answer:
int kthSmallest(TreeNode* root, int k); -> Option A
Quick Check:
Pointer to root + int k parameter = correct signature [OK]
Hint: Use pointer for tree root, int for K [OK]
Common Mistakes:
Passing root by value instead of pointer
Missing K parameter
Wrong return type or missing return
3. Consider the following BST and code snippet. What will be the output?
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int count = 0;
int result = -1;
void inorder(TreeNode* root, int k) {
if (!root) return;
inorder(root->left, k);
count++;
if (count == k) {
result = root->val;
return;
}
inorder(root->right, k);
}
int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(1);
root->right = new TreeNode(4);
root->left->right = new TreeNode(2);
inorder(root, 2);
std::cout << result << std::endl;
return 0;
}
medium
A. 2
B. 1
C. 3
D. 4
Solution
Step 1: Perform in-order traversal on the BST
The BST elements in in-order are visited as: 1, 2, 3, 4.
Step 2: Identify the 2nd element visited
The 1st element visited is 1, the 2nd is 2, so result will be set to 2.
Final Answer:
2 -> Option A
Quick Check:
In-order 2nd element = 2 [OK]
Hint: In-order traversal visits nodes in sorted order [OK]
Common Mistakes:
Confusing pre-order or post-order traversal
Off-by-one error in counting
Not stopping traversal after finding Kth element
4. The following code attempts to find the Kth smallest element in a BST but does not work correctly. What is the main issue?
int count = 0;
int result = -1;
void inorder(TreeNode* root, int k) {
if (!root) return;
inorder(root->left, k);
if (count == k) {
result = root->val;
return;
}
count++;
inorder(root->right, k);
}
medium
A. The function uses global variables which is not allowed
B. The function does not handle null root correctly
C. The result variable is not updated inside the function
D. The check for count == k is before incrementing count, so it misses the Kth element
Solution
Step 1: Analyze the order of count checks and increments
The code checks if count == k before incrementing count, so it skips setting result when count reaches k.
Step 2: Understand impact on finding Kth element
Because count is checked before increment, the Kth element is never assigned to result, causing incorrect behavior.
Final Answer:
The check for count == k is before incrementing count, so it misses the Kth element -> Option D
Quick Check:
Check count after increment, not before [OK]
Hint: Increment count before checking if equals K [OK]
Common Mistakes:
Checking count before incrementing
Ignoring early return after finding Kth element
Assuming global variables cause error
5. You want to find the Kth smallest element in a BST efficiently without using extra space for storing all elements. Which approach is best and why?
A) Perform an in-order traversal and store all elements in a vector, then return the Kth element.
B) Use a recursive in-order traversal with a counter to stop once the Kth element is found.
C) Convert the BST to a sorted array using any traversal and then binary search for the Kth element.
D) Use a breadth-first traversal and count nodes until K is reached.
hard
A. Store all elements then pick Kth; uses extra space
B. Convert to array then binary search; unnecessary overhead
C. Recursive in-order traversal with counter; stops early
D. Breadth-first traversal; does not guarantee sorted order
Solution
Step 1: Evaluate space and time efficiency of each approach
Store all elements then pick Kth; uses extra space to store all elements, which is not efficient. Convert to array then binary search; unnecessary overhead also uses extra space and unnecessary binary search. Breadth-first traversal; does not guarantee sorted order, so it won't find the Kth smallest correctly.
Step 2: Identify the best approach
Recursive in-order traversal with counter; stops early uses recursive in-order traversal which visits nodes in sorted order and stops once the Kth element is found, saving time and space.
Final Answer:
Recursive in-order traversal with counter; stops early -> Option C
Quick Check:
In-order traversal + early stop = efficient Kth smallest [OK]
Hint: Use in-order traversal with counter and stop early [OK]
Common Mistakes:
Using extra space unnecessarily
Using traversal that doesn't preserve order
Not stopping traversal after finding Kth element
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.