Skip to content

Instantly share code, notes, and snippets.

@djvita
Created April 26, 2014 16:53
Show Gist options
  • Save djvita/11324999 to your computer and use it in GitHub Desktop.
Save djvita/11324999 to your computer and use it in GitHub Desktop.
Given a binary search tree, write a method to find the nth smallest element in the tree. For example: Given the Tree: 8 ↙ ↘ 3 10 ↙ ↘ ↘ 1 6 14 ↙ ↘ ↙ 4 7 13 And N = 4, your method would return 6.
using System.Collections.Generic;
public int smallElement(int k)
{
Node<T> node = Root;
int count = k;
int sizeOfSubTree =0;
while (node != null)
{
sizeOfSubTree = node.SizeOfLeftSubTree();
if(sizeOfSubTree +1 == count)
{
return node.Value;
}
else if(sizeOfSubTree +1 < count)
{
node=node.Right;
count -= sizeOfSubTree +1 ;
}
else
{
node = node.Right;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment