Created
April 26, 2014 16:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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