# Find Kth smallest element in binary search tree

Tags: , , , ,

## Kth smallest element in a binary a search tree

Given a binary search tree, find kth smallest element in the binary search tree. For example, 5th smallest element in below binary search tree would be 14, if store the tree in sorted order 5,7,9,10,14,15,19; 14 is the fifth smallest element in that order.

### Kth smallest element in binary search tree: thoughts

As mentioned earlier in a lot of posts like delete a binary tree or mirror a binary tree, first try to find the traversal order required to solve this problem. One hint we already got is that we want all the nodes on BST traversed in sorted order. What kind of traversal gives us a sorted order of nodes? Of course, it is inorder traversal.

So idea is to do an inorder traversal of the binary search tree and store all the nodes in an array. Once traversal is finished, find the kth smallest element in the sorted array.

This approach, however, scans the entire tree and also has space complexity of O(n) because we store all the nodes of tree in an array. Can we avoid scanning the whole tree and storing nodes?

If we keep count of how many nodes are traversed during inorder traversal, we can actually stop traversal as soon as we see k nodes are visited. In this case, we do not store nodes, just a counter.

#### Kth smallest element in binary tree: implementation

```package com.company.BST;

import java.util.Stack;

/**
* Created by sangar on 9.11.18.
*/
public class FindKthSmallestInBST {
private int counter;

public FindKthSmallestInBST(){
counter = 0;
}
public TreeNode findKthSmallest(TreeNode root, int k){
if(root == null) return root;

//Traverse left subtree first
TreeNode left = findKthSmallest(root.getLeft(),k);
//If we found kth node on left subtree
if(left != null) return left;
//If k becomes zero, that means we have traversed k nodes.
if(++counter == k) return root;

return findKthSmallest(root.getRight(),k);
}
}
```

Test cases

```package test;

import com.company.BST.BinarySearchTree;
import com.company.BST.FindKthSmallestInBST;
import com.company.BST.TreeNode;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
* Created by sangar on 23.9.18.
*/
public class KthSmallestElementTest {

FindKthSmallestInBST tester = new FindKthSmallestInBST();

@Test
public void kthSmallestElementTest() {

BinarySearchTree&lt;Integer&gt; binarySearchTree =
new BinarySearchTree&lt;&gt;();
binarySearchTree.insert(10);
binarySearchTree.insert(8);
binarySearchTree.insert(15);
binarySearchTree.insert(12);
binarySearchTree.insert(6);
binarySearchTree.insert(9);

TreeNode kthNode =
tester.findKthSmallest(binarySearchTree.getRoot(),1);
assertEquals(6, kthNode.getValue());
}

@Test
public void kthSmallestElementOnRightSubtreeTest() {

BinarySearchTree&lt;Integer&gt; binarySearchTree =
new BinarySearchTree&lt;&gt;();
binarySearchTree.insert(10);
binarySearchTree.insert(8);
binarySearchTree.insert(15);
binarySearchTree.insert(12);
binarySearchTree.insert(6);
binarySearchTree.insert(9);

TreeNode kthNode =
tester.findKthSmallest(binarySearchTree.getRoot(),5);
assertEquals(12, kthNode.getValue());
}

@Test
public void kthSmallestElementAbsentSubtreeTest() {

BinarySearchTree&lt;Integer&gt; binarySearchTree =
new BinarySearchTree&lt;&gt;();
binarySearchTree.insert(10);
binarySearchTree.insert(8);
binarySearchTree.insert(15);
binarySearchTree.insert(12);
binarySearchTree.insert(6);
binarySearchTree.insert(9);

TreeNode kthNode =
tester.findKthSmallest(binarySearchTree.getRoot(),10);
assertEquals(null, kthNode);
}

@Test
public void kthSmallestElementNulltreeTest() {

BinarySearchTree&lt;Integer&gt; binarySearchTree =
new BinarySearchTree&lt;&gt;();
binarySearchTree.insert(10);
binarySearchTree.insert(8);
binarySearchTree.insert(15);
binarySearchTree.insert(12);
binarySearchTree.insert(6);
binarySearchTree.insert(9);

TreeNode kthNode = tester.findKthSmallest(null,10);
assertEquals(null, kthNode);
}
}
```

The complexity of this algorithm to find kth smallest element is `O(k)` as we traverse only k nodes on binary search tree.

There is hidden space complexity here. Recursive function requires call stack memory, which is limited to Operation System default. More deep you go in recursion, more space we use on stack. If tree is completely skewed, there are more chances of stack overflow. Also recursive function is very difficult to debug in production environments. Below is the non-recursive solution for the same problem.

#### Non-recursive way to find kth smallest element in BST

```public int kthSmallest(TreeNode root, int k) {
Stack&lt;TreeNode&gt; s = new Stack&lt;TreeNode&gt;();

TreeNode current = root;
int result = 0;

while(!s.isEmpty() || current!=null){
if(current!=null){
s.push(current);
current = current.getLeft();
}else{
TreeNode  temp = s.pop();
k--;
if(k==0)
result = (int)temp.getValue();
current = temp.getRight();
}
}

return result;
}
```

Please share if there is something wrong or missing. If you are preparing for an interview and need help, please reach out to us at [email protected]