📖 Scenario: You are working with a simple phone book application that stores contacts in a Binary Search Tree (BST). Each contact has a unique number. You want to find the contact with the kth smallest number to quickly access it.
🎯 Goal: Build a Go program that creates a BST with given numbers, sets a value for k, finds the kth smallest number in the BST, and prints it.
📋 What You'll Learn
Create a BST node struct with integer values
Insert given numbers into the BST
Set an integer variable k for the kth smallest element
Write a function to find the kth smallest element in the BST using in-order traversal
Print the kth smallest element
💡 Why This Matters
🌍 Real World
Finding the kth smallest element is useful in databases and search engines to quickly access ranked data.
💼 Career
Understanding BSTs and traversal algorithms is important for software engineers working on data storage, retrieval, and optimization.
Progress0 / 4 steps
1
Create BST Node and Insert Numbers
Create a struct called Node with an integer Val and pointers Left and Right. Then create a function insert that takes a *Node and an integer val and inserts val into the BST. Finally, create a BST by inserting these numbers in order: 5, 3, 7, 2, 4, 6, 8. Store the root in a variable called root.
DSA Go
Hint
Remember, in a BST, smaller values go to the left child, larger to the right.
2
Set k Value
Create an integer variable called k and set it to 3. This means you want to find the 3rd smallest number in the BST.
DSA Go
Hint
Just create a variable named k and assign it the value 3.
3
Write Function to Find kth Smallest Element
Write a function called kthSmallest that takes root *Node and k int and returns the kth smallest integer in the BST. Use in-order traversal to visit nodes in ascending order. Use a helper function with a counter to find the kth element.
DSA Go
Hint
Use in-order traversal: left child, node, right child. Keep a count and stop when count equals k.
4
Print the kth Smallest Element
In the main function, call kthSmallest(root, k) and print the returned value using fmt.Println.
DSA Go
Hint
Call fmt.Println(kthSmallest(root, k)) to print the result.
Practice
(1/5)
1. What does the term Kth Smallest Element in BST mean?
easy
A. The element with the highest frequency in the BST
B. The element at the root of the BST
C. The largest element in the BST
D. The element that is the Kth smallest when BST elements are sorted in ascending order
Solution
Step 1: Understand BST property
A Binary Search Tree (BST) stores elements so that left child nodes are smaller and right child nodes are larger than the parent node.
Step 2: Define Kth smallest element
The Kth smallest element is the element that appears in the Kth position when all elements are sorted in ascending order.
Final Answer:
The element that is the Kth smallest when BST elements are sorted in ascending order -> Option D
Quick Check:
Kth smallest = Kth element in sorted order [OK]
Hint: Think in sorted order of BST elements [OK]
Common Mistakes:
Confusing Kth smallest with root element
Thinking it means largest element
Mixing frequency with order
2. Which of the following Go function signatures correctly represents a function to find the Kth smallest element in a BST node structure named TreeNode?
easy
A. func kthSmallest(root *TreeNode) int
B. func kthSmallest(root *TreeNode, k int) int
C. func kthSmallest(root TreeNode, k int) *int
D. func kthSmallest(k int, root *TreeNode) int
Solution
Step 1: Check parameter order and types
The function should take the root pointer of type *TreeNode and an integer k to specify the Kth element.
Step 2: Check return type
The function returns an int representing the value of the Kth smallest element.
Final Answer:
func kthSmallest(root *TreeNode, k int) int -> Option B
Quick Check:
Correct parameters and return type [OK]
Hint: Root pointer first, then k, return int [OK]
Common Mistakes:
Swapping parameter order
Passing root by value instead of pointer
Missing k parameter
Wrong return type
3. Given the BST below and k = 3, what will the output of kthSmallest(root, 3) be?
4. Consider this Go function snippet to find the Kth smallest element in a BST:
func kthSmallest(root *TreeNode, k int) int {
count := 0
var result int
var inorder func(node *TreeNode)
inorder = func(node *TreeNode) {
if node == nil {
return
}
inorder(node.Left)
count++
if count == k {
result = node.Val
return
}
inorder(node.Right)
}
inorder(root)
return result
}
What is the main bug in this code?
medium
A. The function does not stop traversal after finding the Kth element
B. The count variable is not incremented correctly
C. The result variable is not returned
D. The inorder function is not called
Solution
Step 1: Analyze traversal stopping condition
The code sets result when count == k but does not stop further recursion, so it continues traversing unnecessarily.
Step 2: Identify missing early return
After finding the Kth element, the function should stop traversing to avoid overwriting result or extra work.
Final Answer:
The function does not stop traversal after finding the Kth element -> Option A
Quick Check:
Traversal continues after Kth found [OK]
Hint: Stop traversal immediately after finding Kth element [OK]
Common Mistakes:
Not stopping recursion after finding result
Incorrect count increment placement
Returning wrong variable
5. You want to find the Kth smallest element in a BST but the tree is very large and you want to optimize the search. Which approach below best improves efficiency?
hard
A. Convert the BST to a sorted array and then pick the Kth element
B. Perform a full in-order traversal every time to find the Kth element
C. Store the count of nodes in each subtree and use it to skip branches
D. Use breadth-first search to find the Kth smallest element
Solution
Step 1: Understand subtree counts
By storing the number of nodes in each subtree, we can decide if the Kth smallest is in left subtree, current node, or right subtree without full traversal.
Step 2: Use counts to skip branches
If left subtree has more than or equal to k nodes, recurse left; else adjust k and recurse right, reducing unnecessary visits.
Final Answer:
Store the count of nodes in each subtree and use it to skip branches -> Option C
Quick Check:
Subtree counts optimize search [OK]
Hint: Use subtree node counts to jump branches [OK]
Common Mistakes:
Doing full traversal every time
Converting to array wastes space/time
Using BFS which is not sorted order
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.