kthSmallestInBST
February 3, 2023
Problem
Note: Your solution should have only one BST traversal and O(1)
extra space complexity, since this is what you will be asked to accomplish in an interview.
A tree is considered a binary search tree (BST) if for each of its nodes the following is true:
 The left subtree of a node contains only nodes with keys less than the node's key.
 The right subtree of a node contains only nodes with keys greater than the node's key.
 Both the left and the right subtrees must also be binary search trees.
Given a binary search tree t
, find the $k^{th}$ smallest element in it.
Note that $k^{th}$ smallest element means $k^{th}$ element in increasing order. See examples for better understanding.
Example

For
t = {"value": 3,"left": {"value": 1,"left": null,"right": null},"right": {"value": 5,"left": {"value": 4,"left": null,"right": null},"right": {"value": 6,"left": null,"right": null}}}and
k = 4
, the output should be
solution(t, k) = 5
.Here is what
t
looks like:3/ \1 5/ \4 6The values of
t
are[1, 3, 4, 5, 6]
, and the $4^{th}$ smallest is5
. 
For
t = {"value": 1,"left": {"value": 1,"left": {"value": 2,"left": null,"right": null},"right": {"value": 0,"left": null,"right": null}},"right": null}and
k = 1
, the output should be
solution(t, k) = 2
.Here is what
t
looks like:1/1/ \2 0The values of
t
are[2, 1, 0, 1]
, and the $1^{st}$ smallest is2
.
Solution
DFS or BFS? BFS starts visiting nodes from root while DFS starts visiting nodes from leaves. So if our problem is to search something that is more likely to closer to root, we would prefer BFS. And if the target node is close to a leaf, we would prefer DFS.
We can use inOrder traversal because the goals is finding $k^{th}$ value from sorted data.
 Create an empty slice as
stack
 Initialize current node as root
 If current is NULL and stack is not empty then
 Push the current node to S and set current = current>left until current is NULL
 Pop the top item from stack.
 Reduce
k
by 1 and return current value ifk==0
 Set current = popped_item>right
 Go to step 3.
 If current is NULL and stack is empty then we are done.