- Published on

# kthSmallestInBST

- Authors
- Name
- Moch Lutfi
- @kaptenupi

## 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

_21t = {_21"value": 3,_21"left": {_21"value": 1,_21"left": null,_21"right": null_21},_21"right": {_21"value": 5,_21"left": {_21"value": 4,_21"left": null,_21"right": null_21},_21"right": {_21"value": 6,_21"left": null,_21"right": null_21}_21}_21}and

`k = 4`

, the output should be`solution(t, k) = 5`

.Here is what

`t`

looks like:_53_5/ \_51 5_5/ \_54 6The values of

`t`

are`[1, 3, 4, 5, 6]`

, and the $4^{th}$ smallest is`5`

.For

_17t = {_17"value": 1,_17"left": {_17"value": -1,_17"left": {_17"value": -2,_17"left": null,_17"right": null_17},_17"right": {_17"value": 0,_17"left": null,_17"right": null_17}_17},_17"right": null_17}and

`k = 1`

, the output should be`solution(t, k) = -2`

.Here is what

`t`

looks like:_51_5/_5-1_5/ \_5-2 0The values of

`t`

are`[-2, -1, 0, 1]`

, and the $1^{st}$ smallest is`-2`

.

## 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 if`k==0`

- Set current = popped_item->right
- Go to step 3.

- If current is NULL and stack is empty then we are done.