Intermediate Level
Implement the kthSmallestInBst method that returns the kth smallest value from a binary search tree.
The input contains a binary search tree, its size, and an integer k.
Your task is to return the kth smallest value in the BST. In a binary search tree, an inorder traversal visits the values in ascending order.
For example, if k is 1, return the smallest value in the tree.
Use inorder traversal because it gives BST values from smallest to largest.
Visit the left subtree first, then the current node, then the right subtree. Count how many valid nodes have been visited. When the count becomes k, the current value is the answer.
This avoids sorting because the BST structure already provides sorted order through inorder traversal.
Pseudocode:
function kthSmallestInBst(tree, size, k):
count = 0
answer = -1
inorder(0)
return answer
function inorder(index):
if index >= size or tree[index] is missing or answer != -1:
return
inorder(2 * index + 1)
count++
if count == k:
answer = tree[index]
return
inorder(2 * index + 2)